1.jpg

    代码如下:

    1. Array.prototype.filter = function(callbackfn, thisArg) {
    2. // 处理数组类型异常
    3. if (this === null || this === undefined) {
    4. throw new TypeError("Cannot read property 'filter' of null or undefined");
    5. }
    6. // 处理回调类型异常
    7. if (Object.prototype.toString.call(callbackfn) != "[object Function]") {
    8. throw new TypeError(callbackfn + ' is not a function')
    9. }
    10. let O = Object(this);
    11. let len = O.length >>> 0;
    12. let resLen = 0;
    13. let res = [];
    14. for(let i = 0; i < len; i++) {
    15. if (i in O) {
    16. let element = O[i];
    17. if (callbackfn.call(thisArg, O[i], i, O)) {
    18. res[resLen++] = element;
    19. }
    20. }
    21. }
    22. return res;
    23. }

    MDN上所有测试用例亲测通过。

    参考:

    V8数组部分源码第1025行

    MDN中filter文档

    三元博客