实现数组方法
用于熟悉数组API底层原理
map()
-
原生实现 map
Array.prototype.myMap = function (fn, thisValue) { if (!Array.isArray(this) || typeof fn !== 'function') { throw new Error('has error') } let result = [] thisValue = thisValue || globalThis let sourceArr = this for (let i = 0; i < sourceArr.length; i++) { result.push(fn.call(thisValue, sourceArr[i], i, sourceArr)) } return result } -
使用 Array 的 reduce 方法
Array.prototype.myMapOfReduce = function (fn, thisValue) { if (!Array.isArray(this) || typeof fn !== 'function') { throw new Error('has error') } const _this = this const result = [] _this.reduce((pre, current, currentIndex, _this) => { result.push(fn.call(thisValue, current, currentIndex, this)) }, undefined) return result }
reduce()
- 原生
Array.prototype.myReduce = function (fn, initValue) { const sourceArr = this const len = sourceArr.length if (!Array.isArray(sourceArr) || typeof fn !== 'function') { throw new Error('has error') } if (len === 0 && initValue === undefined) { throw new Error('Reduce of empty array with no initial value') } let i = initValue === undefined ? 1 : 0 initValue = initValue === undefined ? sourceArr[0] : initValue for (i; i < len; i++) { initValue = fn(initValue, sourceArr[i], i, sourceArr) } return initValue }