Javascript如何计算一系列项目的总价?

时间:2016-11-10 15:26:22

标签: javascript arrays

我是js的新手,我在网上商店购买了一个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; 
    }

2 个答案:

答案 0 :(得分:1)

您正在尝试创建一个关联数组(键/值对),这不是标准数组在JavaScript中的工作方式。

而是创建一个存储数据的对象数组。每个&#34;记录&#34;将作为对象保留,并且这些对象将各自获得一组公共属性名称(在我的示例中为prop1prop2)。然后,您可以循环遍历对象数组,并在每次迭代时,抓住您感兴趣的属性(prop2)。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分: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))
);