I have the 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 a save function, I 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 with Chrome, every ship_object has the correct values in every cycle, but when I print the array, every object has the same values, which are all corresponding to the last one inserted. Literally have no clue why it is happening. Ideas?
Examples of push in JavaScript and common errors Reassigning the array with the output from push is a common error. To avoid this error you need to remember that push changes the array, and returns the new length. If you reassign the variable with the return value from push() you are overwriting the array value.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
The Array. push() method has to be passed a String value, else it will override all values in the array to the last value pushed.
The push() method is used for adding an element to the end of an array.
Basically you are using the reference of the object and updating the same object again and again. Try creating a new object every time when the loop iterates,
function saveAll() {
//while (ship_array.length) { ship_array.pop(); }
ship_array = [];
$(".ship-block").each(function () {
ship_object = {}; // creating a 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);
}
In your code, your array contains references to the same object, you only update properties of that object.
You should create a new object for each array element. Note that you can that using an object literal syntax like so:
function saveAll() {
// Array cleaning
ship_array = [];
// Cyclic save function
$.each($(".ship-block"), function () {
var ship_object = {
builder_id: parseInt($(this).attr("data-counter")),
list_id: list.id,
ship_id: parseInt($(this).attr("data-ship-id"))
};
ship_array.push(ship_object);
});
console.log(ship_array);
}
Note that I also reinitialized the array with a new empty array ([]
) rather than popping from it in a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With