题解 | #要求实现Array.filter函数的功能
请补全JavaScript代码,要求实现Array.filter函数的功能且该新函数命名为"_filter"。
https://www.nowcoder.com/practice/93b96e9694634437898353f844d877af
filter 方法创建一个新数组, 包含通过所提供函数实现的测试的所有元素。
语法:
var newArray = arr.filter(callback(item,index,thisArr))
callback:测试函数
item:当前元素
index:当前索引
thisArr:调用了 filter 的数组本身
newArray:返回的新数组,包含所有通过测试的元素。
实现代码:
Array.prototype._filter=function(callback){ //如果没有传入回调函数,则报错 if(!callback) throw new TypeError('undefined is not a function'); if (typeof callback !== 'function') {//传入的不是函数也报错 throw new TypeError(callback + " is not a function"); } var res=[];//定义返回的新数组 for(var i=0,len=this.length;i<len;i++){ if(callback(this[i],i,this)){//如果函数的返回true,则将当前元素push到返回数组中。 res.push(this[i]); } } return res;//返回新数组 }