是否有相当于 python 'for-else' 循环的 Javascript,所以是这样的:
searched = input("Input: ");
for i in range(5):
if i==searched:
print("Search key found: ",i)
break
else:
print("Search key not found")
还是我只需要求助于一个标志变量,所以是这样的:
var search = function(num){
found = false;
for(var i in [0,1,2,3,4]){
if(i===num){
console.log("Match found: "+ i);
found = true;
}
}
if(!found){
console.log("No match found!");
}
};
请您参考如下方法:
是的,可以在没有标志变量的情况下执行此操作。你可以模仿 for … else
statements使用 label和一个 block :
function search(num) {
find: {
for (var i of [0,1,2,3,4]) {
if (i===num) {
console.log("Match found: "+ i);
break find;
}
} // else part after the loop:
console.log("No match found!");
}
// after loop and else
}
也就是说,我建议不要这样做。这是一种非常规的写法,会导致理解不佳或混淆。早
return
不过是可以接受的,如果您需要在循环后继续执行,可以在辅助函数中使用。