思路
filter 方法接收兩個參數:
- 對每一項執行的函數
- 該函數接收三個參數:
- 數組項的值
數組項的下標
數組對象本身
- 數組項的值
- 該函數接收三個參數:
- 指定 this 的作用域對象
filter 方法返回 執行結果爲true的項組成的數組。
代碼表示:
arr.filter(function(item, index, arr){}, context)
實現
由此,實現 fakeFilter 方法如下
Array.prototype.fakeFilter = function fakeFilter(fn, context) {
if (typeof fn !== "function") {
throw new TypeError("arguments[0] is not a function");
}
let arr = this;
let temp = [];
for (let i = 0; i < arr.length; i++) {
let result = fn.call(context, arr[i], i, arr);
if (result) temp.push(arr[i]);
}
return temp;
};
檢測
let arr = ["x", "y", "z", 1, 2, 3];
console.log(arr.fakeFilter(item => typeof item === "string"));
輸出
[ ‘x’, ‘y’, ‘z’ ]
let arr = ["x", "y", "z", 1, 2, 3];
console.log(arr.filter((item, index, arr) => console.log(item, index, arr)));
輸出
x 0 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
y 1 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
z 2 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
1 3 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
2 4 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
3 5 [ ‘x’, ‘y’, ‘z’, 1, 2, 3 ]
[]