【问题标题】:Javascript Arrays. Pushing a calculated value to an array returns undefinedJavascript 数组。将计算值推送到数组返回未定义
【发布时间】:2014-11-04 12:36:42
【问题描述】:

我创建了一个表单,需要在其中输入数值,然后计算并填充到另一个表单中。然后需要将计算出的输出添加到数组中,以便稍后在会话中参考。

processOrder 函数中的所有数据都已成功推送到各自的数组中,但是一旦我尝试推送任何已计算的数据而不是简单输入的数据,则返回 undefined is not a function。

非常感谢任何帮助。

HTML

<form>
<fieldset>
Units:<input type="number" value="" id="formUnits">   
Kms:<input type="number" value="" id="formKms">   
<input type=button value='Submit Order' onClick='calculate()'>
</fieldset>
</form>

<form>
<fieldset>
Per Unit Costs: <input type="number" id="perUnitCost">
Delivery Charges: <input type="number" id="deliveryCharge">
Pre Tax Total: <input type="number" id="preTaxTotal">
</fieldset>
</form>

JAVASCRIPT

var units = new Array();
var kms = new Array();
var timeStamp = new Array();

var unitCost = new Array();
var delivery  = new Array(); 
var preTax  = new Array();

function calculate(){           
var units = document.getElementById("formUnits").value;           
var kms = document.getElementById("formKms").value;     

if ( units >= 1 && units <= 50 ) 
{
unitCost = 11.1 * units 
} 

if ( kms >= 1 && kms <= 20 ) 
{
delivery = 20
} 

var preTax = unitCost + delivery; 
document.getElementById("perUnitCost").value = unitCost.toFixed(2);   
document.getElementById("deliveryCharge").value = delivery;  
document.getElementById("preTaxTotal").value = preTax.toFixed(2);   

processOrder()

} 

function processOrder(){

units.push(document.getElementById('formUnits').value); 
document.getElementById('formUnits').value=''; 
kms.push(document.getElementById('formKms').value); 
document.getElementById('formKms').value=''; 
timeStamp.push(Date()).value;

add_calcs_to_array()
}

function add_calcs_to_array(){

unitCost.push(document.getElementById('perUnitCost').value); 
document.getElementById('perUnitCost').value='';
delivery.push(document.getElementById('deliveryCharge').value); 
document.getElementById('deliveryCharge').value=''; 
preTax.push(document.getElementById('preTaxTotal').value); 
document.getElementById('preTaxTotal').value=''; 

}

【问题讨论】:

  • 我遇到的一个错误是您将unitCost 定义为一个数组,但在calculate 中您正在为其分配值,因此不再将其设为数组。
  • 那么我应该稍后将其声明为数组吗?
  • 它们是两种不同的变量类型。只需为其中一个选择一个不同的名称。
  • 请将贴出的代码缩小5x-10x。

标签: javascript arrays forms


【解决方案1】:

我看到的问题是您的变量应该在计算中初始化为 var 以隐藏全局变量。像这样:

// This is a global variable.
Var unitCost = [];

function calculate(units) {
  // The var unitCost here occult the global unitCost variable.
  // This means that this unitCost is local to the function.
  var unitCost = 0;
  if (units) {
    unitCost = units * 11.1;
  }
}

calculate(2);
console.log(unitCost); // Still []. Without var in calculate, it would be a 22.2.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多