未捕获到“ .push in array”的TypeError

时间:2019-12-10 21:16:53

标签: javascript arrays push

我正在尝试在.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中抛出的错误

1 个答案:

答案 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();