使用 javascript 在 cookie 中创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4470477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:33:38  来源:igfitidea点击:

Create array in cookie with javascript

javascriptcookies

提问by limfreak

Is it possible to create a cookie using arrays?

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

I would like to store a[0]='peter', a['1']='esther', a['2']='john'in a cookie in JavaScript.

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

回答by Anton Tsapov

As you can read in this topic:

正如您在本主题中所读到的:

You combine the use jQuery.cookieplugin and JSONand solve your problem.

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

When you want to store an array, you create an array in JS and use JSON.stringifyto transform it into an string and stored with $.cookie('name', 'array_string')

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

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

When you want to retrive the array inside the cookie, you use $.cookie('name')to retrive the cookie value and use JSON.parseto retrive the array from the string.

当您想要检索 cookie 内的数组时,您可以使用$.cookie('name')来检索 cookie 值并使用JSON.parse来从字符串中检索数组。

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

回答by Quentin

Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.

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

You could do this with a JSONlibrary.

你可以用一个JSON库来做到这一点。

回答by kingPuppy

I add the code below Script(see the following code) into a javascript file called CookieMonster.js.

我将Script下面的代码(见下面的代码)添加到一个名为 .js 的 javascript 文件中CookieMonster.js

It's a wrapper around the current snippet from http://www.quirksmode.org/js/cookies.html

它是来自http://www.quirksmode.org/js/cookies.html的当前片段的包装器

It works with arrays and strings, it will automagically escape your array/string's commas ,and semi-colons ;(which are not handled in the original snippets).

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

I have listed the simple usage and some bonus usage I built into it.

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

Usage:

用法:

//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;.'

Bonuses:

奖金:

//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 :

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;
        };

回答by Alex

I've created this easy way to get cookies. It'll give error if execute here, but it's functional

我已经创建了这种获取 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();

NewMy new obj to creategetcookies

我的新 obj 到creategetcookie

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');

回答by Nahidul Hasan

Create array in cookie using jQUery?

使用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);
    }

}  });

回答by tatlar

I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:

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

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

You could define a cookie string, then iterate over the array:

您可以定义一个 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;

In this example, you would get the following cookie stored (if your domain is www.example.com):

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

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

回答by Brett

Added remove to cookiemonster

添加移除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);
    };

回答by nobody

For that example you can do it quite easily:

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

  • Make Cookies:

    ///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);
    }
    
  • Retrieve Array:

    for(a=0;a<b.length;a++){
        b[a] = getCookie(b[a])
    }
    
  • 做饼干:

    ///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])
    }
    

For any array with other value types besides strings:

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

  • Make Cookies:

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

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

    ///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)
        }
    }
    

The only flaw is that identical values cannot be retrieved.

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

No JQuery needed, comma seperation or JSON.

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