【问题标题】:How is array map working without passing the parameter?如果不传递参数,数组映射如何工作?
【发布时间】:2021-07-23 00:31:18
【问题描述】:
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]

【问题讨论】:

  • double 是一个函数语句;因此直接作为回调传递给数组的map 方法,该函数将在map 的每个迭代步骤中被调用(的实现)map 本身负责传递正确的参数,item 的当前值, idx, arr 到这个回调函数。
  • map 在示例一中调用double。在示例二中,map 正在调用匿名箭头函数,该函数使用参数调用 double。两者都将当前元素作为其第一个参数传递。
  • 您自己也不要将参数item 传递给函数item => double(item)。您对此很好,但对 double 函数感到困惑?
  • 第二个例子使用了一个箭头函数,它只是将它的单个item 参数转发给double。由于double(item) 的调用是作为箭头函数的一部分发生的,所以double(item) 的返回值自动成为该箭头函数的返回值。

标签: javascript callback


【解决方案1】:

请阅读map documentation

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

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

【讨论】:

    【解决方案2】:

    你可以通过阅读 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)
    

    【讨论】:

    • 只是为了记录......这个polyfill的实现不符合标准/规范,因为它没有处理回调可能的this上下文,它作为@的可选第二个参数提供987654326@ ... arr.map(callback[, thisArg ])
    • @PeterSeliger 我知道,但这足以理解这个案例。 The polyfill from MDN 太复杂了。
    • 我知道你知道,这就是为什么我尽量保持中立和提供信息(并不是说有人会在不阅读规范的情况下开始编写自己的 polyfill)......这就是为什么我会赞成这个 A. 就像我对新贡献者所做的一样。
    【解决方案3】:

    你将一个函数传递给 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-22
      • 2016-02-09
      • 1970-01-01
      • 2023-03-21
      • 2022-06-23
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      相关资源
      最近更新 更多