【问题标题】:When console.log passed as a parameter it works, but when array.push is passed a parameter it doesn't work why?当 console.log 作为参数传递时它可以工作,但是当 array.push 传递参数时它不起作用,为什么?
【发布时间】:2019-08-08 14:32:31
【问题描述】:

我可能会问一个愚蠢的问题。但我是初学者。

我在 eloquent JavaScript 中关于高阶函数的章节中看到了这个例子。

有一个带有 2 个参数的重复函数。 1. 我们想要重复的次数 2. 我们想要重复的动作

当 console.log 作为 2nd 参数传递时,代码工作得很好。它产生完美的输出。

但是当 array.push 作为 2nd 参数传递时,代码会抛出错误,我们需要将函数作为 2nd 参数传递以使 array.push 工作.

请帮助理解这个概念。

//code here works...
function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

repeat(3, console.log);

//so why code below does not work...?
function repeat(n, action) {
    for (let i = 0; i < n; i++) {
      action(i);
    }
  }

let labels = [];
repeat(5, labels.push);

console.log(labels);

/*
In my understanding labels.push is also a function just like console.log, so it should push i 5 times(i.e 0-4) into labels array.
Please help me where am I wrong.
*/

//Why we require to pass a function as described below.
function repeat(n, action) {
    for (let i = 0; i < n; i++) {
      action(i);
    }
  }

let labels = [];
repeat(5, i => labels.push(i));
console.log(labels);

【问题讨论】:

    标签: javascript higher-order-functions array-push


    【解决方案1】:

    这是因为 labels.push 需要上下文。

    如果你这样做repeat(5, labels.push.bind(labels)),你会发现它有效。

    我留给你阅读 fn.call()、fn.bind() 和 fn.apply() 的作用。

    【讨论】:

    • 好的,如果我很愚蠢,我很抱歉,但如果你能详细说明你的第一行,那将非常有帮助。 labels.push 需要上下文是什么意思,为什么 console.log 不需要。
    • push 是附加到对象的实例方法。如果你查看它的内部实现,它会调用this。并且由于重复没有正确的上下文/范围,因此无法找到您首先定义的标签数组。对于 console.log,它是一个不需要上下文的函数。看看这个以更好地理解this :) github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/…
    【解决方案2】:

    执行repeat(5, labels.push.bind(labels)) 有效,但读起来非常糟糕。请改用箭头函数i =&gt; labels.push(i),因为它非常更易于阅读。

    console.log 是全局范围的,所以函数可以访问它。 labels.push 超出了repeat 的范围,因此repeat 无法访问它。如果您想了解箭头函数的工作原理,This page 非常有用

    【讨论】:

      猜你喜欢
      • 2012-03-27
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多