面试有遇到要模拟实现数组方法的,这里做一个简单的总结,以后要了也不定期更新:
map
Array.prototype._map = function(callback) {
const arr = this
const result = []
this.forEach((val, index) => {
result.push(callback.call(arr, val, index, arr))
})
return result
}
Array.prototype._map = function(callback) {
const arr = this
return this.reduce((prev, item, index, arr) => {
prev.push(callback(item, index, arr))
return prev
}, [])
}
reduce
Array.prototype._reduce = function(fn, initval) {
const arr = this
let base = typeof initval === 'undefined' ? arr[0] : initval
let initIndex = typeof initval === 'undefined' ? 1 : 0
arr.slice(initIndex).forEach((val, index) => {
base = fn(base, val, initIndex + index, arr)
})
return base
}
flat
Array.prototype._flat = function(depth = 1){
let res = [...this]
while(depth && res.some(item => Array.isArray(item))) {
res = [].concat(...res)
depth--
}
return res
}