简体   繁体   English

如何通过使用JavaScript / jQuery向存储在cookie中的数组添加/推送新值

[英]How to add/push new value to an array that stored in cookie by using JavaScript/jQuery

I used jQuery to create a cookie album_like that store an array of id , I would like to add/push new value to this array when some condition met, below is my code 我使用jQuery创建了一个cookie album_like来存储id数组,我想在满足某些条件时向该数组添加/推送新值,以下是我的代码

if (typeof $.cookie('album_like') == 'undefined') {
    $.cookie('album_like', [data.album_id], { expires: 365, path: '/' });
} else {
    var arr = [$.cookie('album_like')];
    if (!($.inArray(data.album_id, arr) > 0)) {
        arr.push(data.album_id);
        $.cookie('album_like', arr);
    }
}

I found that the array become ["1, 2, 3, 4, 5"] when I use firebug to check the value, so the code !($.inArray(data.album_id, arr) > 0) not work, I think the array should be [1, 2, 3, 4, 5] . 我发现当我使用萤火虫检查值时,数组变成["1, 2, 3, 4, 5"] ,因此代码!($.inArray(data.album_id, arr) > 0)不起作用,我认为数组应该是[1, 2, 3, 4, 5]

Anyone could give some advice on my code? 有人可以给我一些建议吗?

Thanks 谢谢

This is getting you a string as an array entry not an array. 这使您将字符串作为数组条目而不是数组。

 var arr = [$.cookie('album_like')];

Try this: 尝试这个:

var arr = $.cookie('album_like').split(', '); // split string to array
$.each(arr, function(i,v){
    arr[i] = parseInt(v); // convert string array entries to ints
});

Or you could use json encoding to store and retrieve the array jquery save json data object in cookie 或者您可以使用json编码来存储和检索数组jquery将json数据对象保存在cookie中

 $.cookie.json = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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