ArrayList类(增强版)

时间:2021-05-28

Author:月影
From:http://bbs.51js.com/thread-66469-1-1.html
复制代码 代码如下:
<script>
functionArrayList()
{
varins=Array.apply(this,arguments);
ins.constructor=arguments.callee;
ins.base=Array;

ins.each=function(closure)
{
if(typeofclosure=='undefined')
closure=function(x){returnx};
if(typeofclosure!='function')
{
varc=closure;
closure=function(x){returnx==c}
}

varret=newArrayList();
varargs=Array.apply(this,arguments).slice(1);

for(vari=0;i<this.length;i++)
{
varrval=closure.apply(this,[this[i]].concat(args).concat(i))
if(rval||rval===0)
ret.push(rval);
}

returnret;
}

ins.trim=function()
{
returnthis.each.apply(this);
}

ins.all=function(closure)
{
returnthis.each.apply(this,arguments).length==this.length;
}

ins.any=function(closure)
{
returnthis.each.apply(this,arguments).length>0;
}

ins.contains=function(el)
{
returnthis.any(function(x){returnx==el});
}

ins.indexOf=function(el)
{
varret=this.each.call(this,function(x,i){returnel==x?i:false})[0];
returnret?ret:-1;
}

ins.subarr=function(start,end)
{
end=end||Math.Infinity;
returnthis.each.call(this,function(x,i){returni>=start&&i<end?x:null});
}

ins.valueOf=ins.toString;

ins.toString=function()
{
return'['+this.valueOf()+']';
}

ins.map=function(list,closure)
{
if(typeoflist=='function'&&typeofclosure!='function')
{
varli=closure;
closure=list;
list=li;
}
closure=closure||ArrayList;

returnthis.each.call(this,function(x,i){returnclosure.call(this,x,list[i])});
};

ins.slice=function()
{
returnthis.constructor(ins.base.prototype.slice.apply(this,arguments));
}

ins.splice=function()
{
returnthis.constructor(ins.base.prototype.splice.apply(this,arguments));
}

ins.concat=function()
{
returnthis.constructor(ins.base.prototype.concat.apply(this,arguments));
}

returnins;
}

vara=newArrayList(1,2,3);
alert(a.length);
alert(a);
alert(ainstanceofArray);
alert(a.constructor);
alert(ainstanceofArrayList);//可惜这个值不对,但是没法实现,只好放弃了

alert(a.each(function(x){returnx+x}));
alert(a.all(function(x){returnx>0}));
alert(a.all(function(x){returnx<1}));
alert(a.any(function(x){returnx==2}));

alert(a.contains(2));
alert(a.contains(-1));

varb=a.map([3,2],function(x,y){returnx+y});
alert(b);
alert(a.map([2,3,4]));

alert(a.indexOf(2));
alert(a.indexOf(-1));

alert(a.subarr(1,3));
alert(a.toString());
varb=newArrayList(a,a);
alert(b.toString());
alert(b.slice(1));
</script>
arr.all是当数组(集合)中的所有元素都满足条件时,返回true,否则返回false
arr.any是当数组(集合)中的所有元素中任意一个满足条件时,返回true,如果都不满足,返回false
arr.each返回由符合条件的每一个元素构成的子数组
arr.map是匹配两个数组(集合)并把它们的元素用指定闭包进行计算

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章