2014-11-04 92 views
1

我創建了一個表單,它需要輸入數值,然後計算並填充到另一個表單中。然後計算的輸出需要添加到數組中以供稍後在會話中參考。Javascript數組。將計算值推送到數組返回undefined

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

} 
+0

一個錯誤是你定義'unitCost'作爲一個陣列,但在'calculate'你這樣值分配給它沒有把它的陣列了。 – Andy 2014-11-04 12:43:22

+0

所以我應該稍後將它聲明爲一個數組? – 2014-11-04 12:45:29

+0

它們是兩種不同的變量類型。只需爲其中一個選擇不同的名稱。 – Andy 2014-11-04 12:47:31

回答

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.