简体   繁体   中英

What is happening in this JavaScript ternary operator?

This function creates & stores a cookie, and here it stores the name of the visitor in a cookie variable. According to the source

The parameters of the function hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.

In the function we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

function setCookie(c_name,value,exdays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + 
              ((exdays==null) ? "" : ";expires="+exdate.toUTCString());
  document.cookie=c_name + "=" + c_value;
}

I can see how the Date works, but what is happening in this part:

var c_value=escape(value) + ((exdays==null) ? "" : "; 

Here is the invoking code:

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

I appreciate any tips or advice.

The line is wrapped, here is the full line :

var c_value=escape(value) + ((exdays==null) ? "" : ";expires="+exdate.toUTCString());

this means if the exdays parameter was not specifed ( exdays==null ) then add blank ( "" ) else add ";expires=" plus the date ( exdate ) as a string using toUTCString()

To learn more about cookies use Mozilla MDN instead of w3schools . This kind of if statement is a conditional operator

应该是这样吗?

var c_value=escape(value) + (exdays==null) ? "True Part" : "False Part";

The false part of the ternary has a line break in it at the very end. I guess it should be this:

 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());

instead of:

 var c_value=escape(value) + ((exdays==null) ? "" : "; 
     expires="+exdate.toUTCString());

There appears to be a bad line break in your posted code.

var c_value=escape(value) + ((exdays==null) ? "" : "; 
  expires="+exdate.toUTCString()); // this line should be up after the semicolon

This would then yield:

var c_value=escape(value) + ((exdays==null) ? "" : ";expires="+exdate.toUTCString());

Which basically means if exdays given to the function is null (double equals so it is coerced, which means undefined, empty string, or integer 0 would also fail) then the expiration string would not be concatenated. If an expiration date was given, it would append ";expires="+exdate.toUTCString() to the cookie string.

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