javascript - How to update object properties within a loop? -
i have found behavior did not expect when trying use loop in order change value set property in object.
basically, declare object outside loop. loop on array of numeric values, values used update object property. inside loop, store current object state inside external array.
the result instead of having array containing series of objects different numeric values, end having same numeric values in each object stored.
here fiddle http://jsfiddle.net/faypl/1/
jquery(function(){ var object_container = []; var numeric_values = [1, 2 , 3, 4]; var my_object = {}; jquery.each(numeric_values, function(index, value){ my_object['value'] = value; object_container.push(my_object); }); jquery.each(object_container, function(index, value){ jquery('#content').prepend(value['value']); }); });
i expect 1 2 3 4 values stored in each object, however, 4 4 4 4, not make sense me.
any hint on behavior more welcome, thanks
when code calls .push()
, passes my_object
, what's being passed reference object. no copy made.
thus, you've pushed 4 references exact same object array.
javascript objects participate in expressions in form of references. there's no other way deal objects. when create variable, , set value object, you're setting value reference object. same parameter passing, , anywhere else object can appear in expression.
in case, can create new objects pretty easily; dispense my_object
, push fresh 1 on each iteration:
object_container.push( { value: value } );