Javascript how can I calculate total price in an array of items? -
i'm new js , have cart in webstore making javascript assignment, , can't total price working displays on webpage when user clicks on items add cart. here array of items, appreciated, thank you
var cart; var items = new array(); //create array 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 display function
this.display = function () { this.holder.innerhtml = ""; this.totalprice = 0; (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; }
you trying create associative array (key/value pairs), isn't how standard arrays work in javascript.
instead, create array of objects store data. each "record" persisted object , objects each common set of property names (prop1
, prop2
in example). can loop through array of objects , upon each iteration, grab property interested in (prop2
) in case.
var items = new array(); //create array store items // each item in array store object 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 store total cost // javascript array.prototype specifies built-in method called // foreach takes function argument. function // automatically passed 3 arguments , executed each element // in array. items.foreach(function(value, index, arry){ sum += value.prop2; }); console.log(sum);
Comments
Post a Comment