Reputation: 57
I need to add new variables to an array, that is stored in a cookie. How could i do this ?
var arr = $.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]);
// this is an array of diferent numbers
function pri() { // this function create a number that is not in the array
var n = Math.floor((Math.random() * 15));
var tex;
while ((tex = $.inArray(n, arr)) != -1) {
n = Math.floor((Math.random() * 15));
}
return n;} //i need for whatever "n" is to be added to my array cookie
Upvotes: 1
Views: 3504
Reputation: 318182
The $.cookie plugin will save the array as an string, and this :
var arr = $.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]);
returns the request, something like :
arr=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9
you have to first save the array, then get the string back and split it again, then you can push to it :
$.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]); // set the cookie
var arr = $.cookie("arr").split(','); // get the string and split it
arr.push(pri()); // then add whatever the function returns
now you can save the modified array back in the cookie
$.cookie("arr", arr);
Upvotes: 1
Reputation: 57719
Values in cookies can only be strings so use a (un)serializer.
JSON works fine in JavaScript:
$.cookie("key", JSON.stringify([ 1, 2, 3]);
Usage:
function add_value(new_value) {
var value = JSON.parse($.cookie("key")); // unserialize
value.push(new_value); // modify
$.cookie("key", JSON.stringify(value)); // serialize
}
Upvotes: 0