gpt4 book ai didi

javascript - 如何使用函数构造 JavaScript for 循环

转载 作者:行者123 更新时间:2023-12-01 01:55:25 24 4
gpt4 key购买 nike

我正在用一个函数构建一个循环。

函数loop采用一个值、一个测试函数、一个更新函数和一个主体函数。每次迭代,它首先对当前循环值运行测试函数,如果返回 false,则停止。然后它调用主体函数,为其提供当前值。最终,它调用更新函数创建一个新值并从头开始。

loop(10, n => n > 0, n => n - 1, console.log);

function loop(a, b, c, d) {

let currentValue = a;
let i;
for (i = 0; i < currentValue; i++) {
if (b(currentValue)) {
d(currentValue);
update(c);

function update(c) {
var executeUpdate = c(currentValue);
currentValue = executeUpdate;
};
} else {
return;
}
};
}


// OUTPUT: 10, 9, 8, 7, 6

为什么这个函数停在 6 而不是 1

最佳答案

function update(c) {
var executeUpdate = c(currentValue);
console.log('value of exeucteUpdate: ',executeUpdate, 'when i:', i)
currentValue = executeUpdate;
};

在你的update函数中执行console.log,你会注意到当i == 4时,executeUpdate 是 5 并且您更新了 forloop 的值,因此循环在此特定循环处终止

关于javascript - 如何使用函数构造 JavaScript for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51084622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com