Answer the question
In order to leave comments, you need to log in
What is the correct way to pass an object to a Javascript array?
Good afternoon!
There is the following code:
var item = {}; // Объявляем объект
var items = new Array(); // Объвляем массив
function data_send(n){
var f = $j('#pricelist_'+n); // Находим форму с нужным ID
var i = 0;
f.find('.input').each(function(){ // Находим в форме все элементы с классом input
var val = $j(this).val(); // Получаем значение найденного элемента
if(val != 0){ // если значение не равно 0, то:
item.name = $j(this).parent('td').parent('tr').children('td:first-child').text();
item.amount = $j(this).val();
item.work = $j(this).parent('td').parent('tr').find('.work').text();
item.materials = $j(this).parent('td').parent('tr').find('.materials').text();
item.summary = $j(this).parent('td').parent('tr').find('.summary').text();
items[i] = item; // записываем объект в массив
i = i+1;
}
});
for(j=0;j<i; j++) { // перебираем полученный массив и выводим элементы
alert(JSON.stringify(items[j]));
}
}
Answer the question
In order to leave comments, you need to log in
After n such additions, the array contains n references to the item object. At the time of the output, item has already assumed the state of the "last object", as you called it, which is why the output of the same n times is obtained.
A solution is to declare and initialize item not globally, but inside the callback, in which the object fields are initialized and added to the array.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question