javascript王者が帰ってくるという本の中の一節がアラーに広がっています.
2383 ワード
最近この本を読んでいますが、いい感じです.jsの子供靴を勉強したいです.買ってみてください.
//any ,
// false ,any() , false
Array.prototype.any = function(closure,_set){
//
// each any
_set = _set || false;
// closure
if(typeof closure == 'undefined'){
//
closure = function(x){return x};
};
// closure
if(typeof closure != 'function'){
//
var c = closure;
closure = function(x){return x == c};
};
// 3 ,
var args = Array.apply(this,arguments).slice(2);
//
for(var i=0;i<this.length;i++){
// i closure
var rval = closure.apply(this,[this[i]].concat(args).concat(i));
// boolean ' ' 0
if(rval || rval === 0){
// _set , _set
if(_set && _set.put){
_set.put(rval);
}else{
// ,
return rval;
}
}
}
//
return _set;
};
//each ,
// ,
Array.prototype.each = function(closure){
closure = closure || undefined;
var _set = [];
_set.put = _set.push;
return this.any.apply(this,[closure,_set].concat(Array.apply(this,arguments).slice(1)));
}
// true , true
Array.prototype.all = function(closure){
return this.each.apply(this,arguments).length = this.length;
}
// null,false
Array.prototype.trim = function(){
return this.each();
}
//
Array.prototype.contains = function(el){
return this.any(function(x){ return x==el});
}
// el , , -1
Array.prototype.indexOf = function(el){
return this.any(function(x,i){return el==x ? i : -1});
}
// start end
Array.prototype.subarr = function(start,end){
end = end || Math.Infinity;
return this.each(function(x,i){return i>=start && i<end ? x : null});
}
// , list
// list
Array.prototype.map = function(list,closure){
if(typeof list == 'function' && typeof closure != 'function'){
var li = closure;
closure = list;
list = li;
};
closure = closure || Array;
return this.each(function(x,i){return closure(x,list[i])});
}