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.
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.
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).
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).
Using reduce() JavaScript's reduce() function iterates over the array like forEach() , but reduce() returns the last value your callback returns.
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('');
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With