简体   繁体   中英

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. 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. The first line 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);

it is looking for "name=" and if it finds it removes it from the string. It appends the = to ensure it strips the whole section from string c .

Example: say c = name=SomeCookieName , after that line of code you will be left with SomeCookieName

There are more details here (MDN) , but briefly...

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). 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.

Since that function is searching through all cookies, you need the name plus the equal sign to find the correct value. Without the equal sign, you may get the wrong cookie that has the name you are looking for in its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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