简体   繁体   中英

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 ?

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.

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.

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

您可以使用此:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM