数组映射如何在不传递参数的情况下工作?

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]

请阅读map documentation

map 方法将 3 个参数传递给提供的回调:当前元素、索引和原始数组。

您会在文档中找到所有内容。

你可以通过阅读polyfills的代码来理解这样的事情。 Simplified example:

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)

你传递一个函数给地图函数 所以基本上在 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)