【发布时间】:2019-12-10 21:16:53
【问题描述】:
我正在尝试在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
【问题讨论】:
-
小提琴链接在这里:jsfiddle.net/0r329cas/1
-
totalValue = bill[i] + tip;totalValue.push(u); 失败 -
您的错误原因是您正在设置
totalValue = bill[i] + tip。其中bill[i]是整数,tip是浮点数。所以totalValue现在是一个数字变量,而不是一个数组。 -
tip 在第 19 行定义,任何使用
.push@fubar 的解决方案 -
你为什么要把你显然只是想总结的东西推到一个数组中
标签: javascript arrays push