K
K
Konstantin2015-07-26 14:20:42
JavaScript
Konstantin, 2015-07-26 14:20:42

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])); 
    }

}


The problem is that when we write objects to an array, everything is fine. We write Object 1 into the items[0] cell, Object 2 into the items[1] cell, Object 3 into the items[2] cell, and so on.

But if you run the function for displaying the array elements, then in all its cells it always shows the last object: in the cell items[0] = Object 3, items[1] = Object 3, items[2] = Object 3.

I don’t understand anything how this it turns out ... help me figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2015-07-26
@KoNnY

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 question

Ask a Question

731 491 924 answers to any question