Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  145] [ 5]  / answers: 1 / hits: 35406  / 11 Years ago, mon, february 3, 2014, 12:00:00

Is there a Javascript equivalent of the python 'for-else' loop, so something like this:



searched = input(Input: );
for i in range(5):
if i==searched:
print(Search key found: ,i)
break
else:
print(Search key not found)


Or do I just have to resort to a flag variable, so something like this:



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!);
}
};

More From » javascript

 Answers
22

Working example (you need to use the flag):



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!);
}
};

[#72767] Saturday, February 1, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinley

Total Points: 15
Total Questions: 101
Total Answers: 94

Location: Liechtenstein
Member since Fri, Sep 11, 2020
4 Years ago
;