数组方法重写:forEach, map, filter

Posted ycherry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组方法重写:forEach, map, filter相关的知识,希望对你有一定的参考价值。

Array.prototype.myForEach = function(fn) {
        var arr = this,
          len = arr.length,
          arg2 = arguments[1] || window;
        for(var i = 0; i < len; i++) {
          fn.apply(arg2, [arr[i], i, arr]);
        }
      };

      Array.prototype.myFilter = function(fn) {
        var arr = this,
          len = arr.length,
          arg2 = arguments[1] || window,
          newArr = [];
        for(var i =0; i < len; i++) {
          var item = deepClone(arr[i]);
          fn.apply(arg2, [item, i, arr])? newArr.push(item): ‘‘
        }

        return newArr;
      }

      Array.prototype.myMap = function(fn) {
        var arr = this,
          len = arr.length,
          arg2 = arguments[1] || window,
          newArr = [];
        for(var i =0; i < len; i++) {
          var item = deepClone(arr[i]);
          newArr.push(fn.apply(arg2, [item, i, arr]));
        }
        return newArr;
      }

      function deepClone(source, target) {
        var target = target || {};
        for(var key in source) {
          if(typeof(source[key]) === ‘object‘ && source[key] !== null) {
            if(Object.prototype.toString.call(source[key]) === ‘[object Object]‘) {
              target[key] = {};
            } else if(Object.prototype.toString.call(source[key]) === ‘[object Array]‘) {
              target[key] = [];
            }
            deepClone(source[key], target[key]);
          } else {
            target[key] = source[key]
          }
        }
        return target;
      }

      var arr = [{id: 1}, {id: 2}];
      arr.myForEach(function(item, index, myArr){
        item.id = item.id +1;
      });

      var arrFilter = arr.myFilter(function(item, index, myArr) {
        return item.id > 2;
      });

      var arrMap = arr.myFilter(function(item, index, myArr) {
        return item.id = item.id + 2;
      });

 

以上是关于数组方法重写:forEach, map, filter的主要内容,如果未能解决你的问题,请参考以下文章

数组方法map和forEach的使用方法有哪些?

map和forEach的区别和用法

数组的forEach和map和for方法的区别

js数组的map与forEach方法的区别及兼容性用法

forEach用法与map用法区别

forEach用法与map用法区别