我有一个getter从cookie中获取值。
现在我有了两个cookie,名字分别是shares=和obligation =。
我想让这个getter只从义务cookie中获取值。
我怎么做呢?因此for语句将数据拆分为单独的值,并将其放入数组中。
function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie?
// Because now it searches all the cookies.
var elements = document.cookie.split('=');
var obligations= elements[1].split('%');
for (var i = 0; i < obligations.length - 1; i++) {
var tmp = obligations[i].split('$');
addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
}
}
我会这样做:
function getCookie(cookie){
return cookie
.trim()
.split(';')
.map(function(line){return line.split(',');})
.reduce(function(props,line) {
var name = line[0].slice(0,line[0].search('='));
var value = line[0].slice(line[0].search('='));
props[name] = value;
return props;
},{})
}
这将以对象的形式返回cookie。
然后你可以这样调用它:
getCookie(document.cookie)['shares']
只是为了给这个响应添加一个“正式”的答案,我复制/粘贴解决方案来设置和从MDN检索cookie(这里是JSfiddle
document.cookie = "test1=Hello";
document.cookie = "test2=World";
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
function alertCookieValue() {
alert(cookieValue);
}
在您的特定情况下,您将使用以下函数
function getCookieValue() {
return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}
注意,我只是用“义务”替换了示例中的“test2”。