当控制台.log作为参数传递时,它可以工作,但是当 array.push 传递参数时,它不起作用为什么?



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

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

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

当控制台.log作为第二个参数代码传递时,代码工作正常。 它产生完美的输出。

但是当 array.push 作为第 2 个参数代码抛出错误传递时,我们需要将函数作为第 2参数传递以使 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无法访问它。如果您试图了解箭头函数的工作原理,此页面非常有用

最新更新