检查cookie数组元素是否存在

时间:2015-06-17 07:20:56

标签: javascript jquery cookies js-cookie

如何检查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));
});

2 个答案:

答案 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))
});

请参阅https://github.com/js-cookie/js-cookie/tree/v2.0.2#json