For else loop in Javascript?

后端 未结 7 1445
我寻月下人不归
我寻月下人不归 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:13

    Yes, it is possible to do this without a flag variable. You can emulate for … else statements using a label and a 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
    }
    

    That said, I would recommend against doing this. It is a very unconvential way of writing this and will lead to poor understanding or confusion. An early return is acceptable though, and can be used in a helper function if you need to continue with execution after the loop.

提交回复
热议问题