在数组位置获取并设置cookie值

get and set cookie values in array position

本文关键字:设置 cookie 获取 数组 位置      更新时间:2023-09-26

好的,我有逻辑,但不确定如何写入用管道分隔的cookie中的特定位置,|

例如,以一个具有0|0|0|0 的cookie为例

如果全局变量设置为Y,则将值c和d写入2nd&第三个位置(假设数组)如果cookie存在-如果cookie不存在,则创建一个具有0|0|c|d 的cookie

如果全局变量为null,则将值a和b写入0和第1个位置(如果cookie存在)-如果cookie不存在,则创建具有|b|0|0 的cookie

我理解获取cookie,并拆分cookie以获得值,但不确定如何写入特定位置。我假设使用"join"。

function 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 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 eraseCookie(name) {
    createCookie(name,"",-1);
}

假设您想要的cookie值命名为"pipes",变量命名为globalVar,您可以执行以下操作:

var val = readCookie("pipes") || "";
var valArray = val.split("|");
if (valArray.length >= 4) {
    if (globalVar == "Y") {
        valArray[2] = 'c';
        valArray[3] = 'd';
    } else if (globalVar == null) {
        valArray[0] = 'a';
        valArray[1] = 'b';
    }
    val = valArray.join("|");
} else {
    // fully formed cookie value didn't exist
    if (globalVar == "Y") {
        val = "0|0|c|d";
    } else {
        val = "a|b|0|0";
    }
}
createCookie("pipes", val, 365);

我必须说,将这个管道值存储在cookie中非常不方便,并且需要比从cookie中存储和检索多个值更多的代码。

从您的评论中,听起来数据是storeID|storeLocation,您有其中两个。我建议你这样做:

var store1 = readCookie("store1");    // "1640|Jacob's Point"
var store2 = readCookie("store2");    // "2001|Fred's Point"

或者,如果你想制作一个函数,你可以这样做:

function readStoreInfo(item) {
    var info = readCookie(item);
    if (info) {
        var data = info.split("|");
        return({id: data[0], name: data[1]});
    }
    return(null);
}
function writeStoreInfo(item, obj) {
    var val = obj.id + "|" + obj.name;
    createCookie(item, val, 365);
}

因此,要读取store1的数据,您只需调用:

var store1Info = readStoreInfo("store1");
store1Info.id = 123;
writeStoreInfo("store1", store1Info);

然后,您可以独立地读取和写入store1和store2的数据。