如何更快更简单地了解一个cookie是否具有值或存在?
我使用以下代码来判断是否存在:
document.cookie.indexOf('COOKIENAME=')== -1
了解如何判断是否有值
document.cookie.indexOf('COOKIENAME=VALUE')== -1
有更好的方法吗?这种方法有什么问题吗?
如何更快更简单地了解一个cookie是否具有值或存在?
我使用以下代码来判断是否存在:
document.cookie.indexOf('COOKIENAME=')== -1
了解如何判断是否有值
document.cookie.indexOf('COOKIENAME=VALUE')== -1
显然:
document.cookie.indexOf("COOKIENAME=VALUE");
对我而言,访问cookie的速度更快,但仅略微快一些。
如测试所示,出乎意料的是,将cookie先拆分成数组甚至更快:
document.cookie.split(";").indexOf("COOKIENAME=VALUE");
我建议编写一个小助手函数,以避免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
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;
}
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;
};
使用旧的for循环,可以在找到cookie时提前退出循环,这是它的优势。
查看JSPerf结果,前两种方法并不慢,只有在确实存在对应名称或值的cookie时才会返回true。
希望您能理解我的意思。
我使用Jquery cookie插件来实现此功能。
<script type="text/javascript" src="jquery.cookie.js"></script>
function isCookieExists(cookiename) {
return (typeof $.cookie(cookiename) !== "undefined");
}
MYCOOKIENAME
,并赋值为VALUES
。你认为会发生什么? - zzzzBovfalse
,从而给出错误的结果。 - Moritz Roessler