繁体   English   中英

检查cookie是否存在的更快更短的方法

[英]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

  • 你使用indexOf的方式,只有在你检查cookie中包含String时才会评估它是否正确,它与完整名称不匹配,在这种情况下,上面会返回false,因此会给你错误的结果。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM