For else loop in Javascript?

后端 未结 7 1324
我寻月下人不归
我寻月下人不归 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.

    0 讨论(0)
  • 2021-02-03 21:16

    There is no built-in JavaScript equivalant.

    You can emulate this by using return as a control flow. You can put your for loop in an IIFE and use the return to move beyond conditions afterwards. This does mean that vars don't pollute the scope above with variables.

    (function() {  // Or `(() => {` in ES6  // Python equivalent:
      for (/* for loop body*/) {            // for <loop body>:
        if (/* Condition */) {              //     if <Condition>:
          // Met condition                  //         <Met condition>
          return;  // Goes past the else    //         break
        }                                   // 
      }//else {                             // else:
        // Never met the condition          //     <Never met condition>
    //}
    })();
    

    This has the advantage of not using a flag. It is now inside another function, however, so you cannot declare variables to be used outside. You can still get and set variables in the scope above, so you just have to have the var statements outside of the function.

    A working example for what you wanted to do:

    (function(arr, value) {
      for (var i = 0, length = arr.length; i < length; i++) {
        if (arr[i] === value) {
          console.log("Match found: " + arr[i]);
          return;
        }
      }//else {
        console.log("No match found!");
    //}
    })([0, 1, 2, 3, 4], +prompt("Input: "));

    If you are doing this often, you can create a function to do most of it for you.

    function search(arr, condition, forBody, elseBody) {
      for (var i = 0, length = arr.length; i < length; i++) {
        if (condition(arr[i], arr)) {  // if
          return forBody(arr[i], arr);  // then
        }
      }
      return elseBody(arr);  // else
    }
    
    var value = +prompt("Input: ");
    search([0, 1, 2, 3, 4],
      i => /* if */ i === value,
      i => /* then */ console.log("Match found: " + i),
      () => /* else */ console.log("No match found!"));
    
    0 讨论(0)
  • 2021-02-03 21:16

    You can either use a boolean or you can simply return. Some thing along this line should work...

        var search = function(num){
        found = false;
        for(var i in [0,1,2,3,4]){
            if(i===num){
                console.log("Match found: "+ i);
                return true;
            }
        }
        return false;
    };
    
    0 讨论(0)
  • 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]));
    
    0 讨论(0)
  • 2021-02-03 21:23

    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!");
        }
    };
    
    0 讨论(0)
  • 2021-02-03 21:24

    If your ultimate is goal is to check whether given input is there are not in an array, you can simply make use of indexOf function.

    var arr = [1,2,3,4,5]
    var lookingFor = 5 ; 
    
    if ( arr.indexOf(lookingFor) > -1 ) {
      console.log("Input is here") ;
    } else {
      console.log("Nope");
    }
    
    

    https://jsfiddle.net/7wnasv5e/

    0 讨论(0)
提交回复
热议问题