17

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.

jeffreynolte
  • 3,749
  • 11
  • 41
  • 64
  • 7
    The `return` statement immediately exits a function, returning the value of the expression that follows it. If you use a `return` statement in a loop without some sort of conditional like that it will preform the first pass and then exit. You need to collect them in a variable and return the variable after the loop. As others have suggested you'll probably want to store them in an array. – Useless Code Nov 15 '11 at 05:31
  • Thanks Useless Code after looking into this a bit deeper I see where I was mistaken. Thank you – jeffreynolte Nov 15 '11 at 05:34

3 Answers3

14

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('');
}  
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Shouldn't that be `var values = [];`? – fncomp Nov 15 '11 at 05:22
  • `yield` link is dead. New is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators. Can't edit due to full edit queue. – fabpico Jul 14 '21 at 12:21
2

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;
} 
fncomp
  • 6,040
  • 3
  • 33
  • 42
0
  • 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;
  } 
Awesome
  • 388
  • 3
  • 9