JavaScript中的字符串比较问题

Gam*_*iac 5 javascript pycharm webstorm

当你需要使用Jquery和JavaScript验证用户会话时,我正在查看Django用来获取CSRF令牌的函数.这是代码:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
Run Code Online (Sandbox Code Playgroud)

您也可以看到代码在线这里djangoproject网站上,在这里.

好的,现在当我粘贴这段代码时,我的IDE会收到一个轻微警告:

Binary operation argument type String is not assignable to type HTMLCollection

这是什么意思?错误在这一行:

document.cookie && document.cookie != ''
Run Code Online (Sandbox Code Playgroud)

Rob*_*non 0

第 3 行:

if (document.cookie && document.cookie != '') {
Run Code Online (Sandbox Code Playgroud)

IDE 警告空字符串 '' 是字符串类型,并且空字符串的 != 会隐式转换为 document.cookie 的类型(HTMLCollection 类型)。