问题
Assistance with my code is greatly appreciated. This seems really, really simple but I can't at all see what the problem is. Just for testing purposes, I want to output to the console each of the 9 values of "j"from the inner for loop, as well as each of the 9 values of "i" in the outer for loop, for a total of 81 outputs. But, it's only returning the first value of "j" (9) one time. What am I doing wrong?
var getPalindrome = function(){
for (var i=9;i>0; i--){
for (var j=9;j>0;j--){
return ("J: " + j);
}
return ("I: " + i);
}
}
console.log(getPalindrome());
Output: "J: 9"
回答1:
Don't return from the function on each loop
you want something like this
var getPalindrome = function(){
var retval = ""
for (var i=9;i>0; i--){
for (var j=9;j>0;j--){
retval += "J: " + j + "\n";
}
retval += "I: " + i + "\n";
}
return retval;
}
console.log(getPalindrome());
or
var getPalindrome = function(){
for (var i=9;i>0; i--){
for (var j=9;j>0;j--){
console.log( "J: " + j);
}
console.log("I: " + i);
}
}
getPalindrome();
回答2:
return is not like an echo. It won't return until the process has finished, then will output the last input to the variable. Try document.write or use an array to capture each cycle then output the results after the loop.
来源:https://stackoverflow.com/questions/24004928/javascript-for-loop-only-executed-one-time