javascript for循环在输出中产生错误

时间:2014-05-15 18:58:34

标签: javascript for-loop counter

下面的for循环在html输出中产生错误,我用其他函数代替,并且html输出很好,所以我确信它的这个功能。我也用ide替换了$(“#car”)。html(year); for console.log(year);它产生了正确的输出。这个功能有什么问题?

function cgr() {
for (var year = 0; (churn * total_customer) < leadcon; year++) {
    total_customer = total_customer + leadcon;
     if ((churn * total_customer) >= leadcon) {
            $("#car").html(year);
        }else {
    $("#car").html("something is wrong");
    };
}

}

完整的脚本可以在这里找到:http://pastebin.com/DcDKNfux

1 个答案:

答案 0 :(得分:1)

循环条件,(churn * total_customer)&lt; leadcon,似乎与循环计数器“year”无关,它在零处初始化然后递增。变量churn,total_customer和leadcon在哪里初始化,以及什么值?

在任何情况下,循环条件(churn * total_customer)&lt;输入循环的迭代时,leadcon为true,然后在使用基本上total_customer + = leadcon修改total_customer变量后,if条件(churn * total_customer)&gt; = leadcon)也为true。

但很难知道预期结果是什么,特别是没有关于输入数据的更多信息。

我会在函数中添加更多日志记录,以便您可以跟踪正在发生的事情,如下所示:

function cgr() {
for (var year = 0; (churn * total_customer) < leadcon; year++) {
    $("#car").html("entering loop, year=" + year + ", churn=" + churn + ", total_customer=" + total_customer + ", leadcon=" + leadcon);
    total_customer = total_customer + leadcon;
    $("#car").html("after mod, total_customer=" + total_customer);
     if ((churn * total_customer) >= leadcon) {
            $("#car").html(year);
        }else {
    $("#car").html("something is wrong");
    }
}