【发布时间】:2018-06-28 13:49:10
【问题描述】:
我正在为一个函数构建一个循环。
函数loop 接受一个值、一个测试函数、一个更新函数和一个主体函数。每次迭代,它首先对当前循环值运行测试函数,如果返回 false,则停止。然后它调用 body 函数,给它当前值。最终,它会调用更新函数来创建一个新值并从头开始。
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?
【问题讨论】:
-
b 返回一个布尔值,当前值在您的示例 int 中。你的 if 语句是如何工作的?
if (bool < int) -
@Fallenreaper 对,我刚刚编辑了函数。奇怪的是输出没有机会。
标签: javascript function for-loop