简体   繁体   中英

javascript for loop produces error in output

The below for loop produces an error in the html output, I substituted with other function and the html output was fine, so I'm convinced its this function. I also recreated it in an ide substituting $("#car").html(year); for console.log(year); and it produced the correct output. What is the problem with this function?

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");
    };
}

}

full script can be found here: http://pastebin.com/DcDKNfux

The loop condition, (churn * total_customer) < leadcon, seems to have no relation to the loop counter "year" which is initialized at zero and then incremented. Where are the variables churn, total_customer, and leadcon initialized, and to what values?

In any case, it's completely logical for the loop condition (churn * total_customer) < leadcon to be true when the iteration of the loop is entered, and then for the if condition (churn * total_customer) >= leadcon) to also be true after the total_customer variable is modified with essentially total_customer += leadcon.

But it's hard to know what the expected results are, especially without more information about the input data.

I would add more logging in the function so that you can trace what's happening, something like this:

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM