当 console.log 作为参数传递时它有效,但是当 array.push 作为参数传递时它不起作用,为什么?
When console.log passed as a parameter it works, but when array.push is passed a parameter it doesn't work why?
我可能问的很傻question.but我是初学者
我在 eloquent JavaScript 关于高阶函数的章节中看到了这个例子。
有一个带有 2 个参数的 repeat 函数。
1.我们想要重复的次数
2. 我们要重复的动作
当 console.log 作为 2nd 参数传递时,代码工作得很好。它产生完美的输出。
but when array.push as passed as 2nd argument code throws an error, we are required to pass a function as 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);
这是因为labels.push需要上下文。
如果你这样做 repeat(5, labels.push.bind(labels))
,你会发现它有效。
我留给你阅读 fn.call()、fn.bind() 和 fn.apply() 的作用。
做 repeat(5, labels.push.bind(labels))
可行,但读起来很糟糕。请改用箭头函数 i => labels.push(i)
,因为它 更 更易于阅读。
console.log
是全局范围的,所以函数可以访问它。 labels.push
不在 repeat
的范围内,因此 repeat
无法访问它。如果您想了解箭头函数的工作原理,This page 非常有用
我可能问的很傻question.but我是初学者
我在 eloquent JavaScript 关于高阶函数的章节中看到了这个例子。
有一个带有 2 个参数的 repeat 函数。 1.我们想要重复的次数 2. 我们要重复的动作
当 console.log 作为 2nd 参数传递时,代码工作得很好。它产生完美的输出。
but when array.push as passed as 2nd argument code throws an error, we are required to pass a function as 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);
这是因为labels.push需要上下文。
如果你这样做 repeat(5, labels.push.bind(labels))
,你会发现它有效。
我留给你阅读 fn.call()、fn.bind() 和 fn.apply() 的作用。
做 repeat(5, labels.push.bind(labels))
可行,但读起来很糟糕。请改用箭头函数 i => labels.push(i)
,因为它 更 更易于阅读。
console.log
是全局范围的,所以函数可以访问它。 labels.push
不在 repeat
的范围内,因此 repeat
无法访问它。如果您想了解箭头函数的工作原理,This page 非常有用