[英]Faster and shorter way to check if a cookie exists
知道cookie 是否具有價值或存在的更短更快的方法是什么?
我用這個來知道是否存在 :
document.cookie.indexOf('COOKIENAME=')== -1
這知道是否有價值
document.cookie.indexOf('COOKIENAME=VALUE')== -1
好點? 這個方法有什么問題嗎?
顯然:
document.cookie.indexOf("COOKIENAME=VALUE");
對我來說, 速度更快 ,但只是略微。
正如測試所顯示的那樣,令人驚訝的是,首先將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;
}
這一個,使用原生的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;
};
而且,使用舊的for循環,其優點是能夠在找到cookie時提前返回for循環
看看JSPerf的最后2個甚至不是那么慢,只有當真的是一個名字或值的cookie時才返回true
我希望你明白我的意思
我為此使用Jquery cookie插件 。
<script type="text/javascript" src="jquery.cookie.js"></script>
function isCookieExists(cookiename) {
return (typeof $.cookie(cookiename) !== "undefined");
}
使用此函數檢查cookie是否存在:
function cookieExists(cname) { return (document.cookie.indexOf(cname + '=') == -1) ? false : true; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.