【发布时间】:2020-06-19 18:58:23
【问题描述】:
下面是我试图弄清楚的代码,当在对象方法中声明数组(bill、tipValue、totalAmmount)时,我得到“无法设置属性'0'未定义错误。但是,当在对象方法之外声明相同的数组时对象然后我得到预期的结果”
代码出现异常:
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>
Uncaught Exception: Cannot set Property '0' of undefined
正在运行的代码:
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>
【问题讨论】:
标签: javascript arrays object methods uncaught-exception