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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13747093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:48:05  来源:igfitidea点击:

Faster and shorter way to check if a cookie exists

javascriptcookies

提问by Martin Borthiry

What is the shorter and faster way to know if a cookie has a valueor exists?

知道 cookie是否具有值存在的更短和更快的方法是什么?

I'm using this to know if exists:

我用它来知道是否存在

 document.cookie.indexOf('COOKIENAME=')== -1

This to know if has a value

这要知道是否有价值

 document.cookie.indexOf('COOKIENAME=VALUE')== -1

Any better? Any problems on this method?

好点?这种方法有什么问题吗?

采纳答案by Moritz Roessler

I would suggest writing a little helper function to avoid what zzzzBov mentioned in the comment

我建议编写一个小辅助函数来避免评论中提到的 zzzzBov

  • The way you use indexOf, it would only evaluate correct if you check for the containment of a String in a cookie, it doesn't match a complete name, in that case the above would return false therefore giving you the wrong result.
  • 您使用 indexOf 的方式,如果您检查 cookie 中是否包含字符串,它只会评估正确,它与完整名称不匹配,在这种情况下,上述内容将返回 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


However, this seems to be a bit slow, so giving it an other approach with splitting them Those are two other possibilities

然而,这似乎有点慢,所以给它另一种方法来拆分它们这是另外两种可能性

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;
}

This one, using the native forEach loop and splitting the cookie array

这一个,使用原生 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;
};

And this, using an old for loop, which has the advantage of being able to early return the for loop if a cookie is found

而这个,使用旧的 for 循环,它的优点是如果发现 cookie 能够提前返回 for 循环

Taking a look on JSPerfthe last 2 aren't even that slow and only return true if theres really a cookie with the name or value, respectively

看一下JSPerf,最后 2 个甚至不是那么慢,并且仅在分别具有名称或值的 cookie 时才返回 true

I hope you understand what i mean

我希望你明白我的意思

回答by Cerbrus

Apparently:

显然:

document.cookie.indexOf("COOKIENAME=VALUE");

For me, is faster, but only slightly.

对我来说,速度更快,但只是轻微。

As the test shows, surprisingly, it's even faster to split the cookie up into arrays first:

正如测试所示,令人惊讶的是,首先将 cookie 拆分为数组会更快:

document.cookie.split(";").indexOf("COOKIENAME=VALUE");

回答by trante

I use Jquery cookie pluginfor this.

我为此使用了Jquery cookie 插件

<script type="text/javascript" src="jquery.cookie.js"></script>

function isCookieExists(cookiename) {
    return (typeof $.cookie(cookiename) !== "undefined");
}