是否有相当于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!");
}
};发布于 2014-02-03 10:52:55
工作示例(您需要使用标志):
var search = function(num){
var found = false;
for(var i=0; i<5; i++){
if(i===num){
console.log("Match found: "+ i);
found = true;
break;
}
}
if(!found){
console.log("No match found!");
}
};发布于 2016-05-26 19:31:03
是的,在没有标志变量的情况下可以这样做。您可以使用一个语句和一个块来模拟标签:
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是可以接受的,如果您需要在循环之后继续执行,则可以在助手函数中使用它。
发布于 2021-03-30 11:35:06
您可以使用Array.some()进行测试回调:
if(!items.some( item => testCondition(item) )){
// else statement
}
如果任何元素(或测试)为真,则Array.some()返回true。你可以利用:
下面是一个例子:
const findBigItem = (items) => {
if(!
// for item in items:
items.some( item => {
// here the code for your iteration
// check for the break condition
if ( item > 15) {
console.log("I broke something here: ",item);
return true; // instead of break
}
// by default return null (which is falsy)
})
) { // if no item returned true
// here goes the else statement
console.log("I found nothing!");
}
};
findBigItem([0,1,2,3,4]); //I found nothing!
findBigItem([0,10,20,30,40]); //I broke something here: 20
因此,Array.some()将迭代这些元素,如果任何返回为真,则循环中断(它不会遍历其余的元素)。最后,Array.some()返回的值将充当标志:如果为false,则运行else语句。
所以for else逻辑变成了if not some。
https://stackoverflow.com/questions/21525282
复制相似问题