Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 410
jeffreynolte Avatar asked Nov 15 '11 05:11

jeffreynolte


People also ask

Can I return value from for loop JavaScript?

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.

How do you break out of a for loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

How do I return from a for loop?

It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).

How do you return a value from a forEach loop?

Using reduce() JavaScript's reduce() function iterates over the array like forEach() , but reduce() returns the last value your callback returns.


2 Answers

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('');
}  
like image 90
Gabi Purcaru Avatar answered Oct 09 '22 16:10

Gabi Purcaru


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;
} 
like image 38
fncomp Avatar answered Oct 09 '22 17:10

fncomp