0

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 ?

3
  • 3
    Append to JavaScript arrays with .push(), not by messing with an incrementing index. data.push('some result') Commented Jan 7, 2013 at 21:56
  • Don't set data to an empty string at the end of your click handler. Commented Jan 7, 2013 at 21:57
  • @nnnnnn I know it, and a phone call distracted me from removing my stupid comment Commented Jan 7, 2013 at 22:00

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Probably don't want to resuse the same array with data.length = 0, because then all of the elements of save will point to the same (empty) array...
@nnnnnn: You're right. I lost track of the fact that the save array was getting a reference to the data array. I'll update.
1

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.

Comments

0

You can use this:

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

Comments

0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.