如何检查cookie中是否已存在数组元素?
这是我的代码:
var cookieList = function (cookieName) {
var cookie = Cookies.get(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();
return {
"add": function (val) {
items.push(val);
Cookies.set(cookieName, items.join(','), { path: '/' });
}
}
}
var list = new cookieList("MyItems");
$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
});
答案 0 :(得分:2)
您可以将方法exists
添加到cookieList
,然后使用items
Array.indexOf()
数组中是否存在传递的值
var cookieList = function (cookieName) {
var cookie = Cookies.get(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();
return {
"add": function (val) {
items.push(val);
Cookies.set(cookieName, items.join(','), {
path: '/'
});
},
exists: function (val) {
return items.indexOf(val) > -1
}
}
}
var list = new cookieList("MyItems");
$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
var exists = list.exists(JSON.stringify(imageId))
});
演示:Fiddle
答案 1 :(得分:0)
FWIW,js-cookie开箱即用JSON:
var cookieList = function (cookieName) {
var items = Cookies.getJSON(cookieName) || [];
return {
add: function (val) {
items.push(val);
Cookies.set(cookieName, items);
// "path: /" is default,
// see https://github.com/js-cookie/js-cookie/tree/v2.0.2#path
},
exists: function (val) {
return items.indexOf(val) > -1
}
}
}
var list = new cookieList("MyItems");
$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
var exists = list.exists(JSON.stringify(imageId))
});