gpt4 book ai didi

javascript - 范围问题 - 退出循环

转载 作者:行者123 更新时间:2023-11-29 17:26:17 24 4
gpt4 key购买 nike

我在 javascript 中有以下代码:

var continueloop = true;

while (continueloop === true) {
main()
}

function main() {
//do some stuff here
continueloop = false;
}

在 main 函数中将 continueloop 的值设置为 false 不会导致 while 循环停止。我怀疑这可能与 javascript 的函数作用域有关,但我可能弄错了,有人可以向我解释我必须更改什么,以便使用 main() 函数范围可访问的 continueloop 变量获得预期效果吗?

谢谢!

最佳答案

如果它应该继续,你为什么不直接返回?它更干净,您也不会遇到任何范围问题。

var continueloop = true;

while (continueloop === true) {
    continueloop = main();
}

function main() {
    //do some stuff here
    return false;
}

// or
while(main());

关于javascript - 范围问题 - 退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8526829/

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