我正在尝试在.push
中使用array
概念,这是我尝试过的所有代码的一部分,直到我在.push
循环中添加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 = [];
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
中抛出的错误
答案 0 :(得分:1)
我解决了它,我不必要地创建了另一个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();