javascript - 使用 'this' 关键字时数组的长度不同

标签 javascript arrays this

我开始学习JavaScript,并且写了一小段代码。最终版本如下所示:

var johnCalc = {
  bills: [124, 48, 268, 180, 42],
  tips: [],
  calcTips: function() {
    for (var i = 0; i < this.bills.length; i++) {
      console.log(this.bills.length);
      if (this.bills[i] < 50) tips[i] = 0.2 * this.bills[i];
      else if (this.bills[i] <= 200 && this.bills[i] >= 50) tips[i] = 0.15 * this.bills[i];
      else if (this.bills[i] > 200) tips[i] = 0.1 * this.bills[i];
    }
    console.log(tips);
  }
}

johnCalc.calcTips();

而且效果很好。但在我编写这个正确的案例之前,我在 tips 数组之前使用 this 关键字时犯了一个错误,我的代码如下:

var johnCalc = {
  bills: [124, 48, 268, 180, 42],
  tips: [],
  calcTips: function() {
    for (var i = 0; i < this.bills.length; i++) {
      console.log(this.bills.length);
      if (this.bills[i] < 50) this.tips[i] = 0.2 * this.bills[i];
      else if (this.bills[i] < 200 && this.bills[i] > 50) this.tips[i] = 0.15 * this.bills[i];
      else if (this.bills[i] > 200) this.tips[i] = 0.1 * this.bills[i];
    }
    console.log(tips);
  }
}

johnCalc.calcTips()

这是不正确的,但令我惊讶的是,我在控制台 3 数组的打印元素中收到的结果(在正确的版本中是 5)。尽管我在 tips 数组之前不必要地添加了 this 关键字,但为什么它对 3 个元素有效?我认为它根本不应该起作用。

我正在寻找解释,但找不到答案。为什么在第一种情况下 Tips 数组的长度是 5,而在第二种情况下是 3?您能解释一下这个关键字在这里如何工作吗?

最佳答案

复制并粘贴代码以在控制台中进行测试。然后按照内嵌评论进行操作。

  var tips = ["sandwich"]; // This will be window.tips
  var johnCalc = {
  bills: [124, 48, 268, 180, 42],
  tips: ["pizza"],
  calcTips: function() {
    //tips references the global scope. ie. window.tips
    //tips should show on the console that there is no variable declared.
    //If tips works as "tips" as an array there must be a global tips that is declared.
    //this.tips references johnCalc.tips.
    console.log(window.tips,this.tips);
  }
}

johnCalc.calcTips();

输出将是。

Array [ "sandwich" ] Array [ "pizza" ]

关于javascript - 使用 'this' 关键字时数组的长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713140/

相关文章:

javascript - Node.JS 中的热交换。可能的?

javascript - 这些变量名代表什么?

javascript - 获取选中的行列值extjs网格

javascript - div放置在适当的位置

arrays - 如何在 Swift 中实现过滤功能

java - this的返回值,进一步解释

JavaScript 调用方法

强制转换为 C99 中的指针数组

java - 在重复的字符串中查找任何字符出现的总次数

javascript - react : this is null in event handler