语法
array.filter(function(currentValue,index,arr), thisValue)
- function(currentValue, index,arr)
必须。函数,数组中的每个元素都会执行这个函数
| 参数 | 描述 |
|---|---|
| currentValue | 必须。当前元素的值 |
| index | 可选。当前元素的索引值 |
| arr | 可选。当前元素属于的数组对象 |
- thisValue
可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。
如果省略了 thisValue ,“this” 的值为 “undefined”
简单示例
let arr = ["x", "y", "z", 1, 2, 3];
console.log(arr.filter(item => typeof item === "string"));
动手实现
思路很简单。
- 新建一个数组
- 遍历原数组
- 符合true就加入新数组
- 不符合就跳过
- 返回这个新建的数组
Array.prototype.myFilter = function (func, thisValue) {
if (typeof func !== "function") {
throw new TypeError('${func} is not a function')
}
let arr = thisValue || this;
let result = [];
for (let i = 0; i < arr.length; i++) {
let tmp = func.call(thisValue, arr[i], i, arr);
if (tmp)
result.push(arr[i]);
}
return result;
}
let arr = ["x", "y", "z", 1, 2, 3];
console.log(arr.myFilter(item => typeof item === "string"));
本文深入解析JavaScript中Array.prototype.filter()方法的工作原理,包括其语法、参数及使用场景,并通过动手实现一个简单的myFilter()方法,帮助读者更好地理解和掌握这一核心数组操作技巧。

1484

被折叠的 条评论
为什么被折叠?



