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

It Gives NaN instead of Content of array

这是一个基本的 JavaScript 代码,用于计算给定值的 "tips"。我在这里做错了什么吗?它给我 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;
        }
    }
}

你只需要使用 percentage = value 而不是那些 :

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 = 0;

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

正如其他答案所指出的,根本问题是 percentage: 行。将它们更改为变量赋值 percentage = 0.2; 会修复它。

您可能会问自己 "Why didn't this throw errors?"。

此语法用于定义"label"。标签用于标识使用 breakcontinue 的语句。基本上是一种识别循环的方法,允许您命名要具体中断或继续的循环。 MDN has some good use examples for labels。虽然很少使用,但它是放在你后兜里的东西:)