未捕获的类型错误 " .push in array "



我正在尝试在array中使用.push概念,这是我尝试过的所有事情的代码都很好,直到我在for循环中添加.push

var percentage;
function calculator(bill) {
if (bill < 50) {
percentage = .20;
} else if (bill >= 50 && bill < 200) {
percentage = .15;
} else {
percentage = .1;
}
return percentage * bill;
}
var bill = [250, 112, 45];
function total() {
var totalAmount = [];
var totalValue = [];
for (i = 0; i < bill.length; i++) {
var tip = calculator(bill[i])
totalValue = bill[i] + tip;
console.log("The Tip of " + bill[i] + " is = " + tip + " & the Total Value is " + totalValue);
for (u = 0; u < bill.length; u++) {
totalValue.push(u);
totalAmount.push(totalValue);
}
}
console.log(totalAmount);
}
total();

这是浏览器在控制台Uncaught TypeError: totalValue.push is not a function中抛出的错误

我解决了它,我不必要地创建了另一个 for 循环。

var percentage;
function calculator(bill) {
if (bill < 50) {
percentage = .20;
} else if (bill >= 50 && bill < 200) {
percentage = .15;
} else {
percentage = .1;
}
return percentage * bill;
}
var bill = [250, 112, 45];
function total() {
var totalAmount = new Array();
var totalValue = new Array();
for (i = 0; i < bill.length; i++) {
var tip = calculator(bill[i])
totalValue = bill[i] + tip;
console.log("The Tip of " + bill[i] + " is = " + tip + " & the Total Value is " + totalValue);
totalAmount.push(totalValue);
}
console.log(totalAmount);
}
total();

最新更新