【问题标题】:Uncaught TypeError for " .push in array "“.push in array”的未捕获类型错误
【发布时间】: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


【解决方案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();

【讨论】:

  • 如果您将totalValue 初始化为Array,请不要将其转换为数字totalValue = bill[i] + tip;。这会使您的代码变慢。您可以初始化为 0。例如:var totalValue = 0;
  • 删除var totalValue = new Array();并执行var totalValue = bill[i] + tip;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
  • 2014-12-07
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多