For else loop in Javascript?

后端 未结 7 1322
我寻月下人不归
我寻月下人不归 2021-02-03 20:47

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:
          


        
7条回答
  •  攒了一身酷
    2021-02-03 21:20

    You'll have to use the boolean. There's no for-else in JavaScript.

    A nice and short way to search would be to use Array.prototype.indexOf():

    var search = function(num, arr){
        var index = arr.indexOf(num);
        if(index !== -1)
            return "Match found: " + index;
        }
        return "No match found!";
    };
    

    Call it like this, for example:

    console.log(search(4, [0,1,2,3,4]));
    

提交回复
热议问题