[英]When console.log passed as a parameter it works, but when array.push is passed a parameter it doesn't work why?
I may be asking a silly question.but I am a beginner. 我可能在问一个愚蠢的问题。但我是初学者。
I saw this example in eloquent JavaScript in the chapter about higher order function. 在有关高阶函数的章节中,我用雄辩的JavaScript看到了这个示例。
There is a repeat function that takes 2 arguments. 有一个带有2个参数的重复函数。 1. number of time we want the repetition 2. action that we want to repeat
1.我们想要重复的次数2.我们想要重复的动作
When console.log is passed as 2 nd argument code works just fine. 当console.log作为第二个参数传递时,代码就可以正常工作。 it produces perfect output.
它产生完美的输出。
but when array.push is passed as 2 nd argument code throws an error, we are required to pass a function as 2 nd argument to make array.push work. 但是当array.push作为第二个参数代码引发错误传递时,我们需要传递一个函数作为第二个参数来使array.push工作。
Please help understanding this concept. 请帮助理解这个概念。
//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);
it is because labels.push requires a context. 这是因为labels.push需要上下文。
if you do repeat(5, labels.push.bind(labels))
, you will see that it works. 如果您
repeat(5, labels.push.bind(labels))
,您将看到它起作用。
i leave it to you read up on what fn.call(), fn.bind() and fn.apply() do. 我留给您阅读有关fn.call(),fn.bind()和fn.apply()的内容。
Doing repeat(5, labels.push.bind(labels))
works, but is pretty awful to read. 进行
repeat(5, labels.push.bind(labels))
可以,但是阅读起来很糟糕。 Use your arrow function i => labels.push(i)
instead, because it's much easier to read. 请改用箭头功能
i => labels.push(i)
,因为它更易于阅读。
console.log
is globally scoped, so function can access it. console.log
是全局作用域的,因此函数可以访问它。 labels.push
is out of repeat
's scope, so repeat
is unable to access it. labels.push
不在repeat
的范围内,因此repeat
无法访问它。 This page is very useful if you're trying to understand how arrow functions work 如果您想了解箭头功能的工作原理,则此页面非常有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.