纯自己手写,没考虑到某些情况
语法
array.reduce(function(pre, cur, curIndex, arr), initialValue)
pre:初始值或者上一次的结果值
cur:当前的值
curIndex:当前值的索引
arr:当前执行的数组
initialValue:初始值,可不传,如果传了。pre第一次指的是initialValue,否则,pre第一次指向arry[0]
Map
Array.prototype.newMap = function (fun, thisArg = window) { if (typeof fun !== 'function') { return new Error(fun + 'is not function') } if (!Array.isArray(this)) { return new Error(this + 'is not array') } let newArray = new Array(this.length) if (newArray.length === 0) return []; //谁调用方法,this就指向谁,注意这里的newMap不能写成箭头函数,不然this就指向window console.log(this, 'this') return this.reduce((pre, cur, index, array) => { //这里做稀疏数组判断 if (index in newArray) { pre[index] = (fun.call(thisArg, cur, index, array)) } return pre }, newArray) }Filter
Array.prototype.newFilter = function (fun, thisArg = window) { if (typeof fun !== 'function') { return new Error(fun + 'is not function') } if (!Array.isArray(this)) { return new Error(this + 'is not array') } let newArray = [] console.log(this, 'this') return this.reduce((pre, cur, index, array) => { let item = fun.call(thisArg, cur, index, array) if (item) { pre.push(cur) } return pre }, newArray) }Reduce数组去重
function test(arg) { if (!Array.isArray(arg)) { return new Error( `TypeError:${arg} Must Be Array`) } return arg.reduce((pre, cur) => { if (pre.indexOf(cur) == '-1') { pre.push(cur) } return pre }, []) }Reduce 数组降维。试下flat
function isArray(arg) { if (!Array.isArray(arg)) { return new Error(`TypeError:${arg} Must Be Array`) } }
function newFlat(array) { isArray(array) return array.reduce((pre, cur) => { if (Array.isArray(cur)) { cur = newFlat(cur) } pre = pre.concat(cur) return pre }, []) }