如何修复“未捕获的类型错误:无法设置未定义的属性‘0’" [英] How to fix "Uncaught TypeError: Cannot set property '0' of undefined"
问题描述
下面是我正在尝试找出的代码,当在对象方法中声明数组(bill、tipValue、totalAmmount)时,我得到无法设置属性 '0' 未定义错误.但是,当在外部声明相同的数组时对象然后我得到预期的结果"
Below is the code am trying the figure out, when arrays (bill, tipValue, totalAmmount) are declared within the object method i get "cannot set property '0' undefined error. But, When the same arrays are declared outside the object then i get expected result"
代码出现异常:
var john = {
bill: [124, 48, 268, 180, 42],
tipValue: [],
totalAmmount: [],
calcTip() {
this.bill.forEach(function (ele, i) {
this.tipValue[i] = innercalc(ele);
this.totalAmmount[i] = this.tipValue[i] + ele;
}); //not working code
function innercalc(value) {
if (value < 50)
return value * 0.2;
else if (value > 50 && value < 200)
return value * 0.15;
else if (value > 200)
return value * 0.1;
}
}
}
john.calcTip();
console.log(john.tipValue);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="codingchallange5.js"></script>
</body>
</html>
正在运行的代码:
var tipValue = [];
var totalAmmount = [];
var john = {
bill: [124, 48, 268, 180, 42],
// tipValue: [],
// totalAmmount: [],
calcTip() {
this.bill.forEach(function (ele, i) {
tipValue[i] = innercalc(ele);
totalAmmount[i] = tipValue[i] + ele;
}); //not working code
function innercalc(value) {
if (value < 50)
return value * 0.2;
else if (value > 50 && value < 200)
return value * 0.15;
else if (value > 200)
return value * 0.1;
}
}
}
john.calcTip();
console.log(tipValue);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="codingchallange5.js"></script>
</body>
</html>
推荐答案
使用箭头功能.它不会与 this
混淆,一切都会如你所愿:
Use arrow function. It will not mess with this
and everything will work as you expected:
var john = {
bill: [124, 48, 268, 180, 42],
tipValue: [],
totalAmmount: [],
calcTip() {
this.bill.forEach((ele, i) => { // replace with arrow function here
this.tipValue[i] = innercalc(ele);
this.totalAmmount[i] = this.tipValue[i] + ele;
});
function innercalc(value) {
if (value < 50)
return value * 0.2;
else if (value > 50 && value < 200)
return value * 0.15;
else if (value > 200)
return value * 0.1;
}
}
}
john.calcTip();
console.log(john.tipValue);
来自 MDN: 箭头函数表达式是正则函数表达式的语法紧凑的替代方案,尽管它自己没有绑定到 this
、arguments
、super
或 new.target
关键字.
From MDN: An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this
, arguments
, super
, or new.target
keywords.
这篇关于如何修复“未捕获的类型错误:无法设置未定义的属性‘0’"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!