javascript - 它给出 NaN 而不是数组的内容

标签 javascript arrays nan

这是一个基本的 JavaScript 代码,用于计算给定值的“提示”。我在这里做错了什么吗?它给了我 null 数组或 NaN 而不是我的数组内容。

var john = {

  fullName: 'john smith',
  bills: [124, 48, 32, 268, 180, 42],

  calcTips: function () {
    this.tips = [0];
    this.finalvalue = [0];

    for (var i = 0; i < this.bills.length; i += 1) {
      var percentage;

      if (this.bills[i] < 50) {
        percentage: .2;
      }
      else if (this.bills[i] >= 50 && this.bills[i] < 200) {
        percentage: .15;
      }
      else {
        percentage: .1;
      }

      this.tips[i] = this.bills[i] * percentage;
      this.finalvalue[i] = this.bills[i] + this.bills[i] * percentage;
    }
  }
}

最佳答案

假设 tips 数组中的值已等于 bills 数组中的值数量,并更新 tips 中的相应值 (我可能会补充,这是错误的。稍后介绍)。

但是,由于您仅使用一个值 0 初始化 tips,因此循环在第一次迭代之后没有任何内容可更新。

相反,我建议:


var john = {
    fullName: 'john smith',
    bills: [124, 48, 32, 268, 180, 42],

    calcTips: function() {

        /* I'm assuming you initialized these with one value of 0 because you're doing 
        a calculation later using these, so we'll leave them be */
        this.tips = [0];
        this.finalvalue = [0];

        for ( var i = 0; i < this.bills.length; i+= 1 ) { 
            var percentage;
            /* Reassigning variables requires the equals sign (=) rather than 
            a colon (:) */

            if (this.bills[i] < 50) {
               percentage = .2;
            } else if (this.bills[i] >= 50 && this.bills[i] < 200 ) {
                percentage = .15; 
            } else {
                percentage = .1;
            }

            /* If i is 0, only update the first value of tips (using splice()), past 
            that, push in a new value */
            if (i === 0) {
               this.tips.splice(i, 1, this.bills[i] * percentage ;
            } else {
                this.tips.push(this.bills[i] * percentage);
            } 

            this.finalvalue[i] = this.bills[i] + this.bills[i] * percentage;
        }
    }
}

关于javascript - 它给出 NaN 而不是数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130612/

相关文章:

数组中的 JavaScript 方法

C float32 变量在 64 位系统中显示 nan

python - 如果列包含 NaN,如何将其转换为 int?

c# - 在 float 列表中找到NaN并将上一个和下一个元素设置为NaN

javascript - 如何在文本编辑器中换行(跨度)单词

javascript - jQuery 回调触发得太早

javascript - 我如何从 ext js 中的文件字段获取文件?

javascript - 为什么 Sequelize 发布 "SHOW INDEX FROM ` 表`"?

python - 将 txt 文件转换为 int 数组

C++ 指针数组 : delete or delete []?