You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Array.prototype.newMap=function(fn,context){letnewArr=newArray;if(typeoffn!=="function"){thrownewTypeError(fn+"is not a function");}varcontext=arguments[1];for(vari=0;i<this.length;i++){newArr.push(fn.call(context,this[i],i,this))}returnnewArr}
find
Array.prototype.newFind=function(fn,context){letstr;if(typeoffn!=="function"){thrownewTypeError(fn+"is not a function");}varcontext=arguments[1];for(vari=0;i<this.length;i++){if(fn.call(context,this[i],i,this)){str=this[i];break;}}returnstr}
filter
Array.prototype.newfilter=function(fn,context){letnewArr=newArray;if(typeoffn!=="function"){thrownewTypeError(fn+"is not a function");}varcontext=arguments[1];for(vari=0;i<this.length;i++){if(fn.call(context,this[i],i,this)){newArr.push(this[i])}}returnnewArr}
Activity
NicholasBaiYa commentedon Sep 6, 2019
map
find
filter
HuoXiaoYe commentedon Sep 6, 2019
forEach()方法的实现
map()方法的实现
filter()方法的实现
every()方法的实现
some()方法的实现
xxf1996 commentedon Sep 6, 2019
cyj1209 commentedon Nov 18, 2019
发现大家好像都忽略了两句话
A callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。map和filter 在MDN上都有这么一句话。
B 注意 callback 函数会为数组中的每个索引调用即从 0 到 length - 1,而不仅仅是那些被赋值的索引,这意味着对于稀疏数组来说,该方法的效率要低于那些只遍历有值的索引的方法。 find方法上的关于未赋值元素的说明。
大体的概括一下,array的方法中除了 find,findIndex,lastIndex这三个方法,对于回调方法的调用是属于B类别的。其他的都是属于A类别的。
xiaoqiangz commentedon Jul 15, 2022
Array.prototype.newMap = function(fn) {
let arr = []
for(let i=0;i<this.length;i++) {
arr.push(fn(this[i], i, this))
}
return arr
}
Array.prototype.newFind = function(fn) {
let res = null
for(let i=0;i<this.length;i++) {
res = fn(this[i], i, this)
if (res) {
break
}
}
return res
}
Array.prototype.newFilter = function(fn) {
let arr = []
for(let i=0;i<this.length;i++) {
res = fn(this[i], i, this)
if (res) {
arr.push(this[i])
}
}
return arr
}