数组方法重写: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的主要内容,如果未能解决你的问题,请参考以下文章