码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-12-27 11:38:26      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:===   new   type   pre   span   call   clone   func   ring   

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

标签:===   new   type   pre   span   call   clone   func   ring   

原文地址:https://www.cnblogs.com/ycherry/p/12106123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!