当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JS的数组的扩展实例代码

Javascript
[IE&FireFox兼容]JS对select操作
JS实现全景图效果360度旋转
Unicode 编码转换器
如何用javascript判断录入的日期是否合法
图片从右至左滚动JS
JS控件autocomplete 0.11演示及下载 1月5日已更新
一个对于js this关键字的问题
Javascript标准DOM Range操作全集
兼容Mozilla必须知道的知识。
你所要知道JS(DHTML)中的一些技巧
JS效率个人经验谈(8-15更新),加入range技巧
如何让动态插入的javascript脚本代码跑起来。
Javascript调试工具(下载)
脚本中出现 window.open() access is denied - 拒绝访问 情况一则及分析
Javascript-Mozilla和IE中的一个函数直接量的问题
贴一个在Mozilla中常用的Javascript代码
Javascript miscellanea -display data real time, using window.status
js技巧--转义符"\"的妙用
In Javascript Class, how to call the prototype method.(three method)
Javascript与vbscript数据共享

Javascript 中的 JS的数组的扩展实例代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 314 ::
收藏到网摘: n/a

从无忧转过来的数组的扩展 ,非常不错的把javascript数组的扩展
Array.prototype.del = function(n)
{
if (n<0) return this;
return this.slice(0,n).concat(this.slice(n+1,this.length));
}
// 数组洗牌
Array.prototype.random = function()
{
var nr=[], me=this, t;
while(me.length>0)
{
nr[nr.length] = me[t = Math.floor(Math.random() * me.length)];
me = me.del(t);
}
return nr;
}
// 数字数组排序
Array.prototype.sortNum = function(f)
{
if (!f) f=0;
if (f==1) return this.sort(function(a,b){return b-a;});
return this.sort(function(a,b){return a-b;});
}
// 获得数字数组的最大项
Array.prototype.getMax = function()
{
return this.sortNum(1)[0];
}
// 获得数字数组的最小项
Array.prototype.getMin = function()
{
return this.sortNum(0)[0];
}
// 数组第一次出现指定元素值的位置
Array.prototype.indexOf = function(o)
{
for (var i=0; i<this.length; i++) if (this[i]==o) return i;
return -1;
}
// 移除数组中重复的项
Array.prototype.removeRepeat=function()
{
this.sort();
var rs = [];
var cr = false;
for (var i=0; i<this.length; i++)
{
if (!cr) cr = this[i];
else if (cr==this[i]) rs[rs.length] = i;
else cr = this[i];
}
var re = this;
for (var i=rs.length-1; i>=0; i--) re = re.del(rs[i]);
return re;
}
例子:
var arr=["ni","wo","ta"];
删除数组中的“wo”
var newArr=arr.del(1);
返回数组中“me”第一次出现的位置,若没有就返回-1