以下是浏览器 cookie:
console.log(document.cookie);
//=> name_instagram=true; name_googleplus=true;
这是我的代码:
console.log(document.cookie.split(';').filter( (c) => c.startsWith(parts[1])).map( (d) => d.replace(/.*_(.*)=true/, "$1")));
//=> ["instagram"]
预期结果是["instagram", googleplus]
。我怎样才能得到它?
目前如您所见,只有 cookie 中的最后一项将作为结果值存储到数组中。怎么了?
最佳答案
在 startsWith
过滤器之后,数组中的第二项将为“name_googleplus=true;”,请注意前导空格,因此它以“name_”而不是“name_”开头。解决此问题的一种方法是使用 trim()
删除空格。
console.log(document.cookie.split(';').filter( (c) => c.trim().startsWith('name_')).map( (d) => d.replace(/.*_(.*)=true/, "$1")));
关于javascript - 如何根据cookies创建一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666679/