Javascript数组。将计算值推送到数组将返回undefined

时间:2014-11-04 12:36:43

标签: javascript arrays forms

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

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

任何帮助都非常感激。

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=''; 

}

1 个答案:

答案 0 :(得分:0)

我看到的问题是你的变量应该初始化为计算中的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.