1、回调函数必须是一个函数
2、调用该方法的对象必须是数组。
3. 数组的map方法,其中需要传入两个参数,第一个是一个回调函数,第二个是一个回调函数的this指向的值。
Array.prototype.myMap = function (fn, thisArg) {
if (Object.prototype.toString.call(fn) !== '[object Function]') throw 'Error no Function'
let resArray = []
for (let i = 0; i < this.length; i++) {
resArray[i] = fn.call(thisArg, this[i], i, this)
}
return resArray
}
const arr = [1, 2, 3, 4, 5]
console.log(arr.myMap(item => item * 2)); // [2, 4, 6, 8, 10]
文章介绍了JavaScript中数组的map方法,强调回调函数必须是函数类型,调用对象需为数组。myMap函数实现展示了如何遍历数组并应用回调函数,同时允许指定回调函数的this上下文。示例代码展示了将数组元素乘以2的结果。
936

被折叠的 条评论
为什么被折叠?



