使用javascript在cookie中创建数组

时间:2010-12-17 12:33:10

标签: javascript cookies

是否可以使用数组创建cookie?

我想将a[0]='peter'a['1']='esther'a['2']='john'存储在JavaScript中的Cookie中。

10 个答案:

答案 0 :(得分:46)

正如您可以阅读此topic

您结合使用jQuery.cookie插件和JSON并解决您的问题。

当您想要存储数组时,可以在JS中创建一个数组并使用JSON.stringify将其转换为字符串并与$.cookie('name', 'array_string')一起存储

var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));

如果要在cookie中检索数组,可以使用$.cookie('name')来检索cookie值,并使用JSON.parse从字符串中检索数组。

var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]

答案 1 :(得分:8)

Cookie只能包含字符串。如果要模拟数组,则需要对其进行序列化并对其进行反序列化。

您可以使用JSON库执行此操作。

答案 2 :(得分:3)

我将 脚本 下面的代码(请参阅以下代码)添加到名为CookieMonster.js的javascript文件中。

它是http://www.quirksmode.org/js/cookies.html

当前代码段的封装

它适用于数组和字符串,它会自动转义数组/字符串的逗号,和分号;(未在原始代码段中处理)。

我列出了我内置的简单用法和一些奖励用法。

用法:

//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30); 

var seriesarray = cookiemonster.get('series'); //returns array with the above numbers

//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30); 

var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'

奖金:

//It also conveniently contains splice and append (works for string or array (single string add only)).

//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this' 

//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8'] 

//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']

CookieMonster.js:

        var cookiemonster = new Object();

        cookiemonster.append = function (cookieName, item, expDays) {
            item = cm_clean(item);
            var cookievalue = cookiemonster.get(cookieName);
            if (cookievalue instanceof Array) {
                cookievalue[cookievalue.length] = item;
                cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
            } else {
                cm_createCookie(cookieName, cookievalue + item, expDays);
            }
        };

        cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
            var cookievalue = cookiemonster.get(cookieName);
            if (cookievalue instanceof Array) {
                cookievalue.splice(index, numberToRemove);
                cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
            }
        };



        cookiemonster.get = function (cookieName) {
            var cstring = cm_readCookie(cookieName);
            if (cstring.indexOf('<#&type=ArrayVals>') != -1) {

                var carray = cstring.split(',');

                for (var i = 0; i < carray.length; i++) {
                        carray[i] = cm_dirty(carray[i]);
                }

                if (carray[0] == '<#&type=ArrayVals>') {
                    carray.splice(0, 1);
                }

                return carray;

            } else {

                return cm_dirty(cstring);
            }
        };

        cookiemonster.set = function (cookieName, value, expDays) {
            if (value instanceof Array) {
                cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
            }
            else { cm_createCookie(cookieName, cm_clean(value), expDays); }

        };

        cookiemonster.eraseCookie = function (name) {
            cm_createCookie(name, "", -1);
        };

        function cm_replaceAll(str, find, replace) {

            return str.replace(new RegExp(find, 'g'), replace);
        };

        function cm_clean(ret) {
            ret = cm_replaceAll(ret.toString(), ',', '&#44');
            ret = cm_replaceAll(ret.toString(), ';', '&#59');
            return ret;
        };
        function cm_dirty(ret) {
            ret = cm_replaceAll(ret, '&#44', ',');
            ret = cm_replaceAll(ret, '&#59', ';');
            return ret;
        };

        function cm_createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            } else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        };

        function cm_readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        };

        function cm_arrayAsString(array) {
            var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
            for (var i = 0; i < array.length; i++) {
                    ret = ret + "," + cm_clean(array[i]);
            }
            return ret;
        };

答案 3 :(得分:1)

使用jQUery在cookie中创建数组?

var list = new cookieList("test"); $(img).one('click', function(i){ while($('.selected').length < 3) {
    $(this).parent()
        .addClass("selected")
        .append(setup.config.overlay);

    //$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
    var index = $(this).parent().index();

    // suppose this array go into cookies.. but failed
    list.add( index );

    var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
    if( $('.total').length ){
        $('.total').html(count);
    }

}  });

答案 4 :(得分:1)

我同意其他评论 - 你不应该这样做,你应该使用JSON。但是,要回答您的问题,您可以通过将数组存储为逗号分隔的字符串来解决此问题。假设您想将以下Javascript数组保存到cookie中:

var a = ['peter','esther','john'];

您可以定义一个cookie字符串,然后迭代数组:

// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();

// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';

// Loop over the array
for(var i=0;i<a.length;i++) {
    cookieStr += a[i]+',';
}

// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);

// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;

在此示例中,您将获得以下Cookie存储(如果您的域名是www.example.com):

arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com

答案 5 :(得分:1)

我创建了这种获取Cookie的简便方法。如果在这里执行它会给出错误,但它是有效的

var arrayOfCookies = [];
function parseCookieToArray()
{
    var cookies      = document.cookie;
    var arrayCookies = cookies.split(';');
    arrayCookies.map(function(originalValue){
        var name  = originalValue.split('=')[0];
        var value = originalValue.split('=')[1];
        arrayOfCookies[name] = value;
    });
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();

我对create get Cookie

的新对象
cookie = {
    set: function(name, value) {
        document.cookie = name+"="+value;
    },
    get: function(name) {
        cookies = document.cookie;
        r = cookies.split(';').reduce(function(acc, item){
            let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
            c[0] = c[0].replace(' ', ''); //remove white space from key cookie
            acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
            return acc; //here do not return to r variable, here return to accumulator
        },[]);
    }
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');

答案 6 :(得分:0)

对于这个例子,你可以很容易地做到:

  • 制作Cookie:

    ///W3Schools Cookie Code:
    function setCookie(cname,cvalue,exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";";
    }
    
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    
    ///My Own Code:
    for(a=0;a<b.length;a++){
        setCookie(b[a],b[a],periodoftime);
    }
    
  • 检索数组:

    for(a=0;a<b.length;a++){
        b[a] = getCookie(b[a])
    }
    

对于除字符串之外的其他值类型的任何数组:

  • 制作Cookie:

    ///Replace MyCode above With:
    if(typeof b[a] === 'string'){
        setCookie(b[a],b[a],periodoftime);
    }else{
        setCookie(b[a].toString,b[a],periodoftime);
    }
    
  • 检索数组:

    for(a=0;a<b.length;a++){
        if(typeof b[a] === 'string'){
            b[a] = getCookie(b[a])
        }else{
            b[a] = getCookie(b[a].toString)
        }
    }
    

唯一的缺陷是无法检索到相同的值。

不需要JQuery,逗号分隔或JSON。

答案 7 :(得分:0)

已将删除添加到cookiemonster

// remove item

cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8'] 

    cookiemonster.remove = function (cookieName, item,  expDays) {
        var cookievalue = cookiemonster.get(cookieName);
        //Find the item
        for( var i = 0; i < cookievalue.length; i++) {
            if ( cookievalue[i] === item) { 
                cookievalue.splice(i, 1);
            }
        }
        cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
    };

答案 8 :(得分:0)

这是以数组格式添加 cookie 的最简单形式。

function add_to_cookie(variable, value) {
  var d = new Date();
  d.setTime(d.getTime() + (90 * 24 * 60 * 60 * 1000)); //equivalent to 1 month
  var expires = "expires=" + d.toUTCString();
  document.cookie = "cookie_name[" + variable + "]" + "=" + value + ";" + expires + ';path=/';
}

答案 9 :(得分:-1)

您可以在单个Cookie中保存大量数据,并将其作为数组返回,请尝试

  function setCookie(cookieKey, cookieValue) {
        var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
        var idPurchase = cookie.split(",")
        idPurchase.push(cookieValue)
        document.cookie = cookieKey+"=" + idPurchase
        console.log("Id das compras efetuadas :",idPurchase)
        $("#purchases_ids option:last").after($('<option onclick="document.getElementById("input_class1").value='+cookieValue+'" value="'+cookieValue+'">'+cookieValue+'</option>'))
    }
    checkCookie()
    function checkCookie() {
        var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
        var idPurchase = cookie.split(",")
        console.log("Id das compras efetuadas :",idPurchase)
        for (i = 1; i < idPurchase.length; i++) {
        $("#purchases_ids option:last").after($('<option value="'+idPurchase[i]+'">'+idPurchase[i]+'</option>'))
        }
        purchases_ids.addEventListener("change",changeSpeed)
    }

在我创建的这个项目中,我将值存储在数组中,codePen不允许存储cookie,但是在下面的示例中您可以获得完整的图片,只需研究实现

Github project

Open in Gitpod