【发布时间】: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