2016-11-10 98 views
0

我是js新手,並且在網上商店中有一個購物車,我正在進行Javascript分配,並且當用戶單擊要添加到購物車上的商品時,我無法獲取網頁上顯示的總價格。這裏是我的項目的陣列,任何幫助,將不勝感激,謝謝Javascript如何計算一系列物品的總價格?

var cart; 
var items = new Array(); //create array to store items 
items[0] = "Greatest Hits CD", 10; 
items[1] = "Girls CD", 10; 
items[2] = "Shirt1", 20; 
items[3] = "Mask Tee", 20; 
items[4] = "Crewneck", 25; 
items[5] = "Tour Poster", 9; 

,這裏是我的顯示功能

this.display = function() { 
this.holder.innerHTML = ""; 
this.totalprice = 0; 
for (var i=0; i<this.quantities.length; i++) { 
if (this.quantities[i] > 0) { 
this.totalprice += this.quantities[i]*this.items[i]; 
var elm = document.createElement('div'); 
elm.innerHTML = "<span class='name'>"+this.items[i]+" \</span><span class='quantity'>Quantity: "+this.quantities[i]+"</span>"; 
this.holder.insertBefore(elm, null); 
    } 
} 
var elm = document.createElement('div'); 
elm.innerHTML = "<span class='price'>Total Price: $"+this.totalprice+" </span>"; 
this.holder.insertBefore(elm, null); 
document.getElementById('quantities').value = cart.quantities; 
document.getElementById('items').value = cart.items; 
    } 
+3

你是不是assing,你希望用'項目[0] =什麼「Greatest Hits CD」,10;'更好地使用'物品[0] = [「Greatest Hits CD」,10];',一個數組,不僅麻木呃,這是一個逗號運算符的結果。 –

回答

1

您要創建一個關聯數組(鍵/值對) ,這不是標準數組在JavaScript中的工作方式。

而是創建一個存儲數據的對象數組。每個「記錄」將作爲一個對象持續存在,這些對象將分別獲得一組共同的屬性名稱(在我的示例中爲prop1prop2)。然後,您可以遍歷對象數組,並在每次迭代時,抓取您感興趣的屬性(prop2)。

var items = new Array(); //create array to store items 
 

 
// Each item in the array will store an object with 2 properties 
 
// Object literal syntax: {propertyName : propertyValue, propertyName : propertyValue, etc.} 
 
items[0] = {prop1:"Greatest Hits CD", prop2:10}; 
 
items[1] = {prop1:"Girls CD", prop2:10}; 
 
items[2] = {prop1:"Shirt1", prop2:20}; 
 
items[3] = {prop1:"Mask Tee", prop2:20}; 
 
items[4] = {prop1:"Crewneck", prop2:25}; 
 
items[5] = {prop1:"Tour Poster", prop2:9}; 
 

 
var sum = null; // Place to store the total cost 
 
    
 
// The JavaScript Array.prototype specifies a built-in method called 
 
// forEach that takes a function as an argument. That function is 
 
// automatically passed 3 arguments and is executed for each element 
 
// in the array. 
 
items.forEach(function(value, index, arry){ 
 
sum += value.prop2; 
 
}); 
 

 
console.log(sum);

1

Array Reduce方法,尤其是創建爲:

var items = [ 
 
    ["Greatest Hits CD", 10], 
 
    ["Girls CD", 10], 
 
    ["Shirt1", 20], 
 
    ["Mask Tee", 20], 
 
    ["Crewneck", 25], 
 
    ["Tour Poster", 9] 
 
]; 
 

 
console.log(
 
    items.reduce((a,b) => b[1] + (a[1] ? a[1] : a)) 
 
);