【问题标题】:javascript for loop produces error in outputjavascript for循环在输出中产生错误
【发布时间】:2014-05-15 18:58:33
【问题描述】:

下面的for循环在html输出中产生错误,我用其他函数替换并且html输出很好,所以我确信它的这个函数。我还在 ide 中重新创建了它,替换为 $("#car").html(year);对于 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

【问题讨论】:

  • 什么错误?什么是预期的,这不起作用?您还使用了哪些其他功能有效?
  • 您在 for 循环中更改了 $("#car") 的 html,成功后没有 break; 语句!(为什么?)。
  • 休息会做什么?如果满足条件,则循环停止。
  • 似乎触发了这个错误: function ShowValue (selector, v) { $(selector).html(isNaN(v) ? "Error" : "$" + Round2Cent(v)); }
  • 当然,当您使用字符串(“出现问题”)而不是数字调用 $("#car").html() 函数时,字符串的 isNaN() 会返回 true ,并且该函数仅输出“错误”。不过,我认为这与您的问题并没有真正的直接关系,这就是为什么您要进入代码的“有问题”部分,对吧?

标签: javascript for-loop counter


【解决方案1】:

循环条件 (churn * total_customer)

在任何情况下,循环条件 (churn * total_customer) =leadcon) 也是完全合乎逻辑的在使用 total_customer += leadcon 修改 total_customer 变量后为真。

但是很难知道预期的结果是什么,尤其是在没有关于输入数据的更多信息的情况下。

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

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

【讨论】:

  • 脚本中定义了变量
  • 是的,它们是在脚本中声明的,但我不知道它们有什么值,我也无法调试您的整个客户端脚本。如果您按照我的建议记录值,那么它们的含义会更加明显,并且可能会以与您期望的方式不同的方式处理它们。
  • 这些值由用户在 DOM 的字段中输入。
  • 当然,但同样,如果不对参数进行硬编码,我无法测试该功能。您使用什么值导致失败?同样,以某种方式记录这些内容,即使您无法使用 $("#car").html 函数记录字符串,也将大大有助于调试。
  • 查看此链接以获取 UI,该函数应为“客户获取率”字段生成结果。我已经测试了很多不同的方式,但无法将其输出。 jsfiddle.net/RT6Yn
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2022-01-12
  • 2020-04-18
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多