Mar*_*iry 5 javascript cookies
知道cookie 是否具有价值或存在的更短更快的方法是什么?
我用这个来知道是否存在:
document.cookie.indexOf('COOKIENAME=')== -1
Run Code Online (Sandbox Code Playgroud)
这知道是否有价值
document.cookie.indexOf('COOKIENAME=VALUE')== -1
Run Code Online (Sandbox Code Playgroud)
好点?这个方法有什么问题吗?
我建议编写一个小辅助函数以避免 zzzzBov 在评论中提到的情况
function getCookie (name,value) {
if(document.cookie.indexOf(name) == 0) //Match without a ';' if its the firs
return -1<document.cookie.indexOf(value?name+"="+value+";":name+"=")
else if(value && document.cookie.indexOf("; "+name+"="+value) + name.length + value.length + 3== document.cookie.length) //match without an ending ';' if its the last
return true
else { //match cookies in the middle with 2 ';' if you want to check for a value
return -1<document.cookie.indexOf("; "+(value?name+"="+value + ";":name+"="))
}
}
getCookie("utmz") //false
getCookie("__utmz" ) //true
Run Code Online (Sandbox Code Playgroud)
然而,这似乎有点慢,所以给它另一种方法来分割它们这是另外两种可能性
function getCookie2 (name,value) {
var found = false;
document.cookie.split(";").forEach(function(e) {
var cookie = e.split("=");
if(name == cookie[0].trim() && (!value || value == cookie[1].trim())) {
found = true;
}
})
return found;
}
Run Code Online (Sandbox Code Playgroud)
这个,使用原生的 forEach 循环并分割 cookie 数组
function getCookie3 (name,value) {
var found = false;
var cookies = document.cookie.split(";");
for (var i = 0,ilen = cookies.length;i<ilen;i++) {
var cookie = cookies[i].split("=");
if(name == cookie[0].trim() && (!value || value == cookie[1].trim())) {
return found=true;
}
}
return found;
};
Run Code Online (Sandbox Code Playgroud)
这使用了旧的 for 循环,其优点是如果找到 cookie 就能够提前返回 for 循环
看看JSPerf,最后两个甚至没有那么慢,并且只有在确实存在具有名称或值的 cookie 时才返回 true
我希望你明白我的意思