Reputation: 2104
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
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
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
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
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