forEach
- 作用: 循环遍历数组
- 特点:
- 不改变原数组,返回值为undefined。
- 改变不了数组的遍历(return/break不好使,会报错)
- 源码实现
Array.prototype.myForEach = function(func) { var len = this.length; for(var i = 0; i < len; i++) { func(this[i], i); } } 复制代码
filter
- 作用: filter筛选数组,筛选出新的数组。
- 特点: 筛选的值由return来决定,会放在一个新的数组中返回。
- 源码实现
Array.prototype.myFilter = function(func) { var len = this.length, newArr = []; for(var i = 0; i < len; i++) { if(func(this[i], i)) { newArr.push(this[i]); } } return newArr; } 复制代码
map
- map和filter的区别:
- filter要的是ele
- map要的是return出来的结果
- 特点:
- map处理return出来的值,把值放在一个新的数组,默认返回undefined。
- 浅拷贝,会改变原数组。
- 浅度map实现
Array.prototype.myMap = function(func) { var len = this.length, newArr = []; for(var i = 0; i < len; i++) { newArr.push(func(this[i], i)); } return newArr; } 复制代码
- 深度map实现
// 深度克隆 function deepClone(target, option) { if(option !== null) { for(var prop in option) { var src = target[prop], copy = option[prop]; if(typeof(copy) === 'object') { if(Object.prototype.toString(copy) === '[object Array]') { src = []; }else { src = {}; } target[prop] = deepClone(src, copy); }else { target[prop] = copy; } } } return target; } Array.prototype.myMap = function(func) { var len = this.length, newArr = []; for(var i = 0; i < len; i++) { if(this[i] && Object.prototype.toString.call(this[i]) === '[object Object]') { var newObj = {}; deepClone(newObj, this[i]); newArr.push(func(newObj, i)); }else if(this[i] && Object.prototype.toString.call(this[i]) === '[object Array]') { var Arr = []; deepClone(newArr, this[i]); newArr.push(func(Arr, i)); }else { newArr.push(func(this[i], i)); } } return newArr; } 复制代码
reduce
-
作用: 迭代数组,从左向右,累加器(效率高)。
-
源码实现
Array.prototype.myMap = function(func, init) { var k = 0, prev = init, len = this.length; if(init === undefined) { prev = this[0]; k = 1; } for(k; k < len; k++) { prev = func(prev, this[k], k); } return prev; }; 复制代码
reduce
- 特点: 类似reduce 从右向左
- 源码实现
Array.prototype.myReduceRight = function(func, init) { var prev = init, len = this.length, k = len - 1; if(init === undefined) { prev = this[k]; k = len - 2; } for(k; k >= 0; k --) { prev = func(prev, this[k], k); } return prev; }
作者:William陈
链接:https://juejin.im/post/5d932a8151882562d61bb71c
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。