简体   繁体   English

您可以向我解释一下Javascript Cookie教程的这一行代码吗?

[英]Can you explain to me about this line of code for Javascript cookie tutorial?

I'm just beginning to learn javascript and while I was going through the cookie tutorial, there is a part which I don't understand at all. 我才刚刚开始学习JavaScript,而在我学习Cookie教程时,有一部分我根本不了解。 Can you guys please explain it to me in detail? 你们能给我详细解释一下吗? Thanks in advance! 提前致谢!

Below's the whole script but the only part which puzzles me is the readCookie(name) function. 以下是整个脚本,但令我感到困惑的唯一部分是readCookie(name)函数。 The first line var nameEQ = name + "="; 第一行var nameEQ = name + "="; I don't understand why we have to put an equal sign to the end of the string. 我不明白为什么我们必须在字符串末尾加上等号。

function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

At first glance: 乍一看:

In this line: if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 在这一行: if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

it is looking for "name=" and if it finds it removes it from the string. 它正在寻找"name=" ,如果找到它将从字符串中删除。 It appends the = to ensure it strips the whole section from string c . 它附加=以确保从字符串c删除整个部分。

Example: say c = name=SomeCookieName , after that line of code you will be left with SomeCookieName 示例:say c = name=SomeCookieName ,在该行代码之后,您将剩下SomeCookieName

There are more details here (MDN) , but briefly... 这里有更多详细信息(MDN) ,但简要...

At minimum, a cookie is a string that consists of the name of the cookie (the part before the equal sign) and the value of the cookie (the part after the equal sign). cookie至少是一个字符串,它由cookie的名称(等号之前的部分)和cookie的值(等号之后的部分)组成。 So, the equal sign is just the divider between name and value. 因此,等号只是名称和值之间的分隔符。 This way the cookie can be stored as a string but contain multiple parts. 这样,cookie可以存储为字符串,但包含多个部分。

Since that function is searching through all cookies, you need the name plus the equal sign to find the correct value. 由于该功能正在搜索所有cookie,因此您需要名称加上等号才能找到正确的值。 Without the equal sign, you may get the wrong cookie that has the name you are looking for in its value. 没有等号,您可能会得到错误的Cookie,该Cookie的名称与您要查找的名称相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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