ECMA262规范如下:
代码如下:
代码语言:javascript复制Array.prototype.filter = function(callbackfn, thisArg) {
// 处理数组类型异常
if (this === null || this === undefined) {
throw new TypeError("Cannot read property 'filter' of null or undefined");
}
// 处理回调类型异常
if (Object.prototype.toString.call(callbackfn) != "[object Function]") {
throw new TypeError(callbackfn ' is not a function')
}
let O = Object(this);
let len = O.length >>> 0;
let resLen = 0;
let res = [];
for(let i = 0; i < len; i ) {
if (i in O) {
let element = O[i];
if (callbackfn.call(thisArg, O[i], i, O)) {
res[resLen ] = element;
}
}
}
return res;
}
MDN上所有测试用例亲测通过。
参考:
V8数组部分源码第1025行
MDN中filter文档