jeffreynolte
jeffreynolte

Reputation: 3779

Returning values out of for loop in javascript

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];
    }    
  }                          

and when using console.log() within the function instead of return I get all of the values in the loop, and the same goes for document.write. How can I access these values as a string for use in another section of my code?

Thank you in advance.

Upvotes: 18

Views: 74761

Answers (3)

Awesome
Awesome

Reputation: 388

  • 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;
  } 

Upvotes: 0

fncomp
fncomp

Reputation: 6188

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

Upvotes: 2

Gabi Purcaru
Gabi Purcaru

Reputation: 31564

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('');
}  

Upvotes: 16

Related Questions