JavaScript for循环仅执行一次 [英] JavaScript for loop only executed one time

查看:104
本文介绍了JavaScript for循环仅执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢您提供我的代码.这似乎非常非常简单,但我根本看不出问题出在哪里.仅出于测试目的,我想将内部for循环的"j"的9个值中的每个以及外部for循环的9个"i"值中的每个输出到控制台,总共81个输出.但是,它仅一次返回"j"(9)的第一个值.我在做什么错了?

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());


输出:"J:9"


Output: "J: 9"

推荐答案

不要在每次循环时从函数中返回

Don't return from the function on each loop

您想要这样的东西

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());

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();

这篇关于JavaScript for循环仅执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆