[英]How is array map working without passing the parameter?
const arr2 = arr.map(double)
如果没有我传递数组项,这是如何工作的? 我需要将参数传递给函数 double:类似double(item)
东西。
let arr = [1, 2, 3, 4, 5] function double(x) { return x * 2 } const arr2 = arr.map(double) const arr3 = arr.map(item => double(item)) console.log("arr2= ", arr2) console.log("arr3= ", arr3)
输出:
arr2 = [2, 4, 6, 8, 10]
arr3 = [2, 4, 6, 8, 10]
你可以通过阅读 polyfills 的代码来理解这样的事情。 简化示例:
Array.prototype.myMap = function(callbackFn) {
const arr = [];
for (let i = 0; i < this.length; i++) {
// call the callback function for every value of this array
// and push the returned value into our resulting array
arr.push(callbackFn(this[i], i, this));
}
return arr;
}
在你的情况下:
// for arr2
callbackFn === function double(x) {
return x * 2
}
// for arr3
callbackFn === (item) => double(item)
您将一个函数传递给 map 函数,因此基本上在arr3
map 函数中,您使用箭头语法创建了一个新的匿名函数,该函数激活了内部的 double 函数,但您没有给它实际发生在 map 函数中的项目
let arr = [1, 2, 3, 4, 5] function double(x) { return x * 2 } const arr2 = arr.map(double) const arr3 = arr.map(item => double(item)) // This is a new function that you created console.log("arr2= ", arr2) console.log("arr3= ", arr3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.