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.
asked Nov 15, 2011 at 5:17
jeffreynolte
3,77911 gold badges43 silver badges65 bronze badges
3 Answers 3
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('');
}
answered Nov 15, 2011 at 5:20
Gabi Purcaru
31.7k9 gold badges81 silver badges96 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
fncomp
Shouldn't that be
var values = [];?fabpico
yield link is dead. New is developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…. Can't edit due to full edit queue.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;
}
answered Nov 15, 2011 at 5:21
fncomp
6,2084 gold badges36 silver badges43 bronze badges
Comments
- 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
lang-js
returnstatement immediately exits a function, returning the value of the expression that follows it. If you use areturnstatement 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.