时间:2021-07-01 10:21:17 帮助过:5人阅读
Object.prototype.extend = function(src){
for(var i in src){
this[i] = src[i];
}
}
Array.extend({
toArray : function(arrayLike){
try{
return [].slice.call(arrayLike);
}catch(ex){
var ret = [];
for(var i = 0,len = arrayLike.length ; i < len ; i++){
ret.push(arrayLike[i]);
}
}
},
isArray : (Array.isArray)?Array.isArray:function(ele){
return ele.constructor == Array;
}
})
Array.prototype.extend((function(){
var each = Array.prototype.forEach || function(fn,obj){
for(var i = 0,len = this.length ; i < len ; i++){
fn.call(obj,this[i]);
}
};
var filter = Array.prototype.filter || function(fn,obj){
var result = [];
for(var i = 0,len = this.length ; i < len ; i++){
if(fn.call(obj,this[i])){
result.push(this[i]);
}
}
return result;
};
var every = Array.prototype.every || function(fn,obj){
for(var i = 0,len = this.length ; i < len ; i++){
if(!fn.call(obj,this[i])){
return false;
}
}
return true;
};
var some = Array.prototype.some || function(fn,obj){
for(var i = 0,len = this.length ; i < len ; i++){
if(fn.call(obj,this[i])){
return true;
}
}
return false;
};
var indexOf = Array.prototype.indexOf || function(dest){
for(var i = 0; i < this.length ;i++){
if(dest == this[i]){
return i;
}
}
return -1;
};
var map = Array.prototype.map || function(fn,obj){
var result = [];
for(var i = 0,len = this.length ; i < len ; i++){
result.push(fn.call(obj,this[i]));
}
return result;
};
var reduce =Array.prototype.reduce || function(fn,init){
var result = init || this[0];
for(var i = 0; i < this.length; i++){
result = fn(result,this[i]);
}
return result;
}
return {
map : map,
each : each,
some : some,
every : every,
filter : filter,
indexOf: indexOf,
reduce : reduce
}
})())
下面是一个小例子,给指定ul下面的li设置内容:
代码如下:
<ul id="test">
<li></li>
<li></li>
<li></li>
</ul>
<script type="text/javascript">
Array.prototype.slice.call(document.getElementById('test').getElementsByTagName('li'),0).each(function(li){
li.innerHTML = '测试each';
})
</script>