我有一個函數,它可以計算訂單的總報價,然後將訂單的報價提醒用戶。我也希望將總引號存儲在一個數組中,這樣就可以調用一個單獨的函數,它將顯示數組中的所有值(顯示自頁面加載以來的所有引號)。從我可以計算出來的數組中,當函數結束時,函數將失去由函數推入的值,而且我已經玩過陣列的範圍而沒有任何喜悅,並且會讚賞向正確方向微調。Javascript - 函數關閉時的數組清空值
<form>
<table id="kit" cellpadding="2" cellspacing="5">
<th colspan="2" align="center"><h3>Purchase Shirts (Coming Soon)</h3></th>
<tr><td class="titles">Size</td>
<td class="titles">Qty</td></tr>
<tr><td>Small (£10)</td>
<td><input type="text" size="3" maxlength="5" name="small" /></td>
<tr><td>Medium (£12)</td>
<td><input type="text" size="3" maxlength="5" name="medium" /></td>
<tr><td>Large (£15)</td>
<td><input type="text" size="3" maxlength="5" name="large" /></td>
<tr><td>X-Large (£20)</td>
<td><input type="text" size="3" maxlength="5" name="xlarge" /></td>
<tr><td colspan="2" align="center">
<input class="submit" type="submit" onClick="return calculateShirts(this)" value="Get Quote" /></td>
</tr>
</table>
</form>
的JavaScript ------------
var totalQuotes = [1,2]; //Initialise the global array with example values
function calculateShirts(form) //Function to calculate shirt 'quote'
{
//Assign Prices for Each Shirt Size
var sml = 10;
var med = 12;
var lge = 15;
var xl = 20;
//Save the user inputs as variables
var smlQu = form.small.value;
var medQu = form.medium.value;
var lgeQu = form.large.value;
var xlQu = form.xlarge.value;
//Multiply the Price by the User Input and save as variable
var smlQuote = (sml * smlQu);
var medQuote = (med * medQu);
var lgeQuote = (lge * lgeQu);
var xlQuote = (xl * xlQu);
//Add the calculated values together to get the total price
var finalQuote = (smlQuote + medQuote + lgeQuote + xlQuote);
//Create an array containing the quotes
var arrayQuote = [smlQuote, medQuote, lgeQuote, xlQuote, finalQuote];
//Variable containing the formatted output of quotes
var output = "Your Kit Quote \n\n Small - £" + arrayQuote[0] + "\n" + "Medium - £" + quoteArray[1] + "\n" + "Large - £" + quoteArray[2] + "\n" + "X-Large - £" + quoteArray[3] + "\n\n" + "Total - £" + quoteArray[4];
//Display the output variable in a popup box
alert(output);
totalQuotes.push(finalQuote);
alert(totalQuotes); //This alert does show the calculated value
return false;
}
function printQuotes() //Function called on to display array values
{
for (i in totalQuotes) {
alert(totalQuotes[i]);
//The calculated value is no longer in the array
}
}
不要使用'for in'循環數組,請使用'for(idx; test; inc)'。 'for in'是爲了迭代Objects的屬性。 – meouw
變量arrayQuote似乎指的是你沒有提到的全局變量。 – Jivings
這只是我忘記刪除的一個小提琴,對不起。我原本只是立即提醒整個陣列。 – IckleChris