JavaScript for loop only executed one time

丶灬走出姿态 提交于 2021-02-05 11:49:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!