ES5 数组方法封装
2020-01-28 本文已影响0人
鹤仔z
forEach
Array.prototype.myForEach = function(callback){ if(typeof callback !== 'function'){ throw new Error(callback + 'is not function'); } let T = arguments[1] ? arguments[1] : window; for(let i = 0 ; i < this.length ; i ++){ callback.call(T,this[i],i,this) } }
map
Array.prototype.myMap = function(callback){ if(typeof callback !== 'function'){ throw new Error(callback + 'is not function'); } let T = arguments[1] ? arguments[1] : window; let res = []; for(let i = 0 ; i < this.length ; i ++){ res.push(callback.call(T,this.[i],i,this)); } return res; }
filter
Array.prototype.myFilter = function(callback){ if(typeof callback !== 'function'){ throw new Error(callback + 'is not function'); } let T = arguments[1] ? arguments[1] : window; let res = []; for(let i = 0 ; i < this.length ; i ++){ if(callback.call(T,this[i],i,this)){ res.push(this[i]); } } return res; }
reduce
Array.prototype.maReduce = function(callback,I){ if(typeof callback !== 'function'){ throw new Error(callback + 'is not function'); } var isI = false; var res; if(I){ isI = true; res = I; } for(var i = 0 ; i < this.length ; i ++){ if(isI){ res = callback(res,this[i],i,this) }else{ res = this[i]; isI = true; } } return res; }