javascript - Inserting an object to a global array? -


i have html file form person fill out take order.

i have global array store objects. objects contain name, price, , quantity of item added order.

<button type="button" onclick="addtoorder('app2-amount', 'house salad', '6')">+</button>  

this addtoorder() called.

and function:

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 must perform check see if object same name exists in order    // if exist, replace 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 not logged in:    else{    console.log("you not logged in. please log in use feature.");     }  console.log(menuobject); } 

when print menuobject, thought out of scope, deleted. inserting global variable, , think screwing me over.

some odd things happen when starting putting different menu items array. in 1 case, added 3, 6, 12, 24, etc. each press. kinda funny, i'm pretty bummed.

what happens here?

you've misunderstood lexical scoping in javascript, think.

var declarations scoped @ function block level. means though var statement inside of if block, has scope throughout entire function, , remains defined until function exits. they're valid everywhere in function (even before declaration), due hoisting.

if you're writing in es6, can use let declarations, scoped nearest enclosing block...in case, if block. that'd behavior think expecting here.

your other issue logical. each pass through function, you're using foreach traverse array, , potentially pushing new object once every existing object in array. that's why you're getting geometric progression in array length.

if intent 'replace matching item in array if it's there, otherwise add end' there couple ways can that. array.find 1 option, there several approaches that'd work.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -