Returning values out of for loop in javascript

后端 未结 3 1345
悲哀的现实
悲哀的现实 2020-12-28 18:43

I have the following function:

  function getId(a){
    var aL = a.length;
    for(i = 0; i < aL; i++ ){
      return a[i][2].split(\":\", 1)[0];
    }            


        
相关标签:
3条回答
  • 2020-12-28 19:00

    You gotta cache the string and return later:

    function getId(a){
        var aL = a.length;
        var output = '';
        for(var i = 0; i < aL; i++ ){
           output += a[i][2].split(":", 1)[0];
        }    
        return output;
    } 
    
    0 讨论(0)
  • 2020-12-28 19:03

    You can do that with yield in newer versions of js, but that's out of question. Here's what you can do:

    function getId(a){
      var aL = a.length;
      var values = [];
      for(i = 0; i < aL; i++ ){
        values.push(a[i][2].split(":", 1)[0]);
      }    
      return values.join('');
    }  
    
    0 讨论(0)
  • 2020-12-28 19:10
    • The return statement breaks the loop once it is executed. Therefore consider putting the return statement outside the loop.
    • Since you want to return a string, you will create a variable and assign it to an empty string.(This is where will append/add results from the loop.)
    • return the string variable.

    So final code will look like...

    function getId(a){
        var result = '';
        var aL = a.length;
        for(i = 0; i < aL; i++ ){
          result += a[i][2].split(":", 1)[0];
        } 
        return result;
      } 
    
    0 讨论(0)
提交回复
热议问题