我开始学习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个元素有效?我认为它根本不起作用。
我正在寻找解释,但找不到答案。为什么在第一种情况下,技巧数组的长度为5,而在第二种情况下,为何为3?您能在这里解释一下这个关键字如何工作吗?
答案 0 :(得分:1)
将代码复制并粘贴到控制台中进行测试。然后按照内联注释进行操作。
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”]