gpt4 book ai didi

javascript - 为什么我无法跳出这个 for 循环?

转载 作者:行者123 更新时间:2023-12-02 14:03:51 25 4
gpt4 key购买 nike

这是对一个网站的测试,我检查照片源是否存在,如果不存在,我想隐藏显示这些照片(如果存在)的额外面板。问题是我无法得到 breakVar = true; 状态,循环也不会停止,我尝试了不同的方法来让它通过中断/返回停止。

我测试 testPhotos(currentProduct,display,breakVar); 的输出,并且我想获得“测试失败”返回,以便我可以隐藏额外的面板。

是的,当我拼命尝试检查代码执行过程中的状态时,代码变得很难看。

我尝试将 break; 语句放在不同的位置,但收到“非法的break语句”错误

我在控制台中循环测试失败 8 次。

var breakVar = false;

function triggerPhotoFail(breakVar) {
breakVar = true;
consol.log('triggerPhotoFail ran');
return "test-fail";
}
function testPhotos(currentProduct,display,breakVar) {
for (var i = 0; i < 5; i++) {
// test if photos exists
if (breakVar === true) {
break; // get out of loop
}
var src = productArray[currentProduct]['subphoto-' + i];
$.get(src)
.done(function() {
// photo exists
})
.fail(function(breakVar) {
// photo does not exist
console.log('test failed in loop');
breakVar = true;
triggerPhotoFail();
console.log('breakVar change!: ' + breakVar);
})
}
if (breakVar === true) {
console.log('breaker var tested true');
return "test-fail";
}
else {
return "not acknowledged";
}
}

最佳答案

$.get 是异步的。在调用 donefail 函数之前,循环已完成。

您需要将 for 循环替换为一个迭代器,当 done 函数触发时该迭代器会前进。

function testPhotos(currentProduct, display) {
// This starts the loop
var i = 0; next();

function next() {
// This replaces the regular "end of for loop" check
if (i == 5) {
return;
}

$.get(src)
.done(function() {
// photo exists
i++; next(); // This does the "End of for loop increment" test and starts the next loop
})
.fail(function(breakVar) {
// photo does not exist
console.log('test failed in loop');
triggerPhotoFail();
// We don't call `next()` here, which breaks the loop
});

}
}

关于javascript - 为什么我无法跳出这个 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40212670/

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