《JavaScript 高级程序设计》中对map方法这样定义: 对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
Array.prototype._map = function (fn) {
const _arr = []
if (!Array.isArray(this) || this.length < 1 || typeof fn !== 'Function') return
for (let i = 0; i < this.length ; i ++) {
_arr.push(fn(this[i], i, this))
}
return _arr
}
const arr = [1, 2, 3]
arr._map((item, index, arr) => {
return item+1
})
// [2, 3, 4]