javascript - Array.push replaces all my array elements with the last one inserted -


i have following code:

var ship_array = new array();  var ship_object = new object();     ship_object.builder_id = 0;     ship_object.list_id = 0;     ship_object.ship_id = 0;     ship_object.title_id = 0; 

then in save function, do:

function saveall() {     // array cleaning     while (ship_array.length) { ship_array.pop(); }      // cyclic save function     $.each($(".ship-block"), function () {         ship_object.builder_id = parseint($(this).attr("data-counter"));         ship_object.list_id = list.id;         ship_object.ship_id = parseint($(this).attr("data-ship-id"));         ship_array.push(ship_object);     });     console.log(ship_array); } 

while debugging chrome, every ship_object has correct values in every cycle, when print array, every object has same values, corresponding last 1 inserted. literally have no clue why happening. ideas?

basically using reference of object , updating same object again , again. try creating new object every time when loop iterates,

function saveall() {     //while (ship_array.length) { ship_array.pop(); }     ship_array = [];     $(".ship-block").each(function () {         ship_object = {}; // creating new object here!!         ship_object.builder_id = parseint($(this).attr("data-counter"));         ship_object.list_id = list.id;         ship_object.ship_id = parseint($(this).attr("data-ship-id"));         ship_array.push(ship_object);     });     console.log(ship_array); } 

Comments

Popular posts from this blog

How to show in django cms breadcrumbs full path? -

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -