Johnny000
Johnny000

Reputation: 2104

jquery saving data in array

I want to save and add on every click data to an array. I tried this

var data = [];
var save = [];
s=0;
i=0;

some called function(){
  data[i++] = some result;
  data[i++] = some other result;
}

$('#someelement').click(function(){
save[s++] = data;
console.log(save); // for debugging
i = 0;
data = '';
});

The first save works, but after that I just empty arrays added. Any pointers ?

Upvotes: 0

Views: 1575

Answers (5)

httpworld
httpworld

Reputation: 84

You should use [] to create new array.

Here is working example:

<script>
   var data = [];
   var save = [];
   s=0;
   i=0;

function addRes(){
    data[i++] = 'some result';
    data[i++] = 'some other result';
}

$('#someelement').click(function(){
    addRes();
    save[s++] = data;
    console.log(save); // for debugging
    i = 0;
    data = [];
});
</script>

Upvotes: 0

user234932
user234932

Reputation:

You might want to try making a copy of the data array:

save[s++] = data.slice(0);

This way, whatever happens to data array wont affect the save array's items.

Upvotes: 1

the system
the system

Reputation: 9336

It's because you're replacing the Array with a string.

data = '';

You should replace it with a new Array instead.

data = [];

Or reuse the data Array by adding a shallow copy of data to save, then clearing data.

save[s++] = data.slice();

data.length = i = 0;

This allows any other code that has a reference to data to retain its reference so that it is always viewing the data that is being updated.

Upvotes: 3

Grinn
Grinn

Reputation: 5543

If you're trying to add the current contents of data to a single element in save, use Array.push:

$('#someelement').click(function(){
    save.push(data);
    console.log(save); // for debugging
    i = 0;
    data = [];
});

...or if it's that you want the current values in data added to save, use Array.concat, resetting data back to an empty array:

$('#someelement').click(function(){
    save = save.concat(data);
    console.log(save); // for debugging
    data = [];
});

Upvotes: 0

Hosein
Hosein

Reputation: 581

You can use this:

data[data.length] = <some value>;

Upvotes: 0

Related Questions