Skip to content
Advertisement

Javascript how can I calculate total price in an array of items?

I’m new to js and have a cart in a webstore I am making for a Javascript assignment, and I can’t get my total price working which displays on the webpage when the user clicks on items to add to the cart. Here is my array of items, any help would be appreciated, thank you

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;

and here is my display function

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; 
    }

Advertisement

Answer

You are trying to create an associative array (key/value pairs), which isn’t how standard arrays work in JavaScript.

Instead, create an array of objects that store the data. Each “record” will be persisted as an object and those objects will each get a common set of property names (prop1 and prop2 in my example). You can then loop through the array of objects and upon each iteration, grab the property you are interested in (prop2) in this case.

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement