从本质上讲,我有一个完整的操纵up脚本,最后,我将其记录为页面cookie并返回给我:
[ { name: 'cookie_name',
value: 'I WANT THIS VALUE ONLY',
domain: 'cookie domain',
path: '/',
expires: -1,
size: 43,
httpOnly: true,
secure: true,
session: true } ]
该数组存储为变量 sessionCookies ,而我要做的只是记录cookie值,该值在上面显示为“仅我想要此值”。
我正在寻找类似于console.log(sessionCookies.cookie_name.value);
的东西,但是我愿意接受任何解析或任何其他解决方案,感谢您的帮助!
答案 0 :(得分:0)
您可以过滤cookie名称,并找到第一个条目。 喜欢:
let sessionCookies = [{
name: 'name_of_the_cookie_you_want_to_get',
value: 'I WANT THIS VALUE ONLY',
domain: 'cookie domain',
path: '/',
expires: -1,
size: 43,
httpOnly: true,
secure: true,
session: true
}]
let myCookieValue = sessionCookies.filter(function(cookie) {
return cookie.name === 'name_of_the_cookie_you_want_to_get'
})[0].value
console.log(myCookieValue)
但是请注意,如果未找到cookie或cookie不存在,它将使数组超出范围。
答案 1 :(得分:0)
另一种非ES6解决方案:
const sessionCookies = [
{
name: 'cookie_name',
value: 'I WANT THIS VALUE ONLY',
domain: 'cookie domain',
path: '/',
expires: -1,
size: 43,
httpOnly: true,
secure: true,
session: true
}
];
console.log(findCookie('cookie_name'));
function findCookie(name) {
for (let i in sessionCookies) {
if (!sessionCookies.hasOwnProperty(i)) {
continue;
}
if (sessionCookies[i].name === name) {
return (sessionCookies[i].value);
}
}
}
forEach()
,filter()
,find()
等数组方法的问题在于无法停止其迭代,因此在某些情况下它们的性能较低。