我有一個表格的HTML文件來填寫一個人來接受訂單。我有一個全局數組來存儲對象。這些對象包含添加到訂單的項目的名稱,價格和數量。將對象插入全局數組?
<button type="button" onclick="addToOrder('app2-amount', 'House Salad', '6')">+</button>
這是調用addToOrder()的地方。
而且功能:
var orderArray = [];
function addToOrder(id, nameIn, priceIn){
if (loggedIn == true){
var quantityIn = document.getElementById(id).value;
var totalForThisItem = priceIn*quantityIn;
var menuObject = {
name: nameIn,
price: totalForThisItem,
quantity: quantityIn
};
// Next we must perform a check to see if an object with the same name already exists in the order
// If it does exist, replace it with this new object.
if (orderArray.length == 0){
orderArray.push(menuObject);
}
else{
orderArray.forEach(function (item) {
if (item.name == menuObject.name){
item = menuObject;
}
else{
orderArray.push(menuObject);
}
});
}
console.log("dabs " + orderArray.toString());
}
// If user is not logged in:
else{
console.log("You are not logged in. Please log in to use this feature.");
}
console.log(menuObject);
}
當我打印menuObject,我認爲這將是超出範圍,刪除。我將它插入到一個全局變量中,我認爲它正在把我搞砸。
當我開始將不同的菜單項放入數組時,會發生一些奇怪的事情。在一個案例中,每增加一個新聞,它就會增加3,6,12,24等等。有趣,但我很沮喪。
這裏會發生什麼?
'當我打印menuObject時,我認爲它會超出範圍,刪除'因爲你打印它的功能(最後),它還沒有超出範圍。除此之外,你的問題不清楚你的問題究竟是什麼?將一些示例/場景與數據進行解釋。 – TheUknown
當我將不同的菜單項添加到列表中時,會出現奇怪的現象。 我也很習慣Java編碼,我沒有意識到它沒有超出函數的範圍(認爲最後一個括號是類結尾)。 但它超出了範圍。這是否意味着什麼? – kaleoh
嘗試將'item = menuObject;'改爲'item.name = menuObject.name; item.price = menuObject.price; item.quantity = menuObject.quantity'或者直接插入到數組中 – TheUknown