After experimenting with the code below, I discovered that when arrays (bill, tipValue, totalAmmount) are declared within the object method, I encounter a "cannot set property '0' undefined" error. However, if the same arrays are declared outside the object, I achieve the expected result.
Code throwing exception:
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
Working code snippet:
var tipValue = [];
var totalAmmount = [];
var john = {
bill: [124, 48, 268, 180, 42],
calcTip() {
this.bill.forEach(function (ele, i) {
tipValue[i] = innercalc(ele);
totalAmmount[i] = tipValue[i] + ele;
}); //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>