18

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.

2
  • 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. Commented Nov 15, 2011 at 5:31
  • Thanks Useless Code after looking into this a bit deeper I see where I was mistaken. Thank you Commented Nov 15, 2011 at 5:34

3 Answers 3

16

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('');
}  
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't that be var values = [];?
yield link is dead. New is developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…. Can't edit due to full edit queue.
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;
} 

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.