javascript - 这个 JavaScript 三元运算符发生了什么?

标签 javascript cookies ternary-operator

该函数创建并存储一个 cookie,这里它将访问者的姓名存储在 cookie 变量中。根据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;
}

我可以看到日期是如何工作的,但这部分发生了什么:

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

调用代码如下:

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

感谢任何提示或建议。

最佳答案

该行已换行,这是完整的行:

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

这意味着如果未指定 exdays 参数 (exdays==null),则添加空白 (""),否则添加 ";expires=" 加上日期 (exdate) 作为字符串,使用 toUTCString()

了解有关 cookie 的更多信息 use Mozilla MDN而不是w3schools 。这种 if 语句是 conditional operator

关于javascript - 这个 JavaScript 三元运算符发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9873537/

相关文章:

javascript - 求三 Angular 形面积? "Undefined"如果 num < 0

javascript - 在 svg 容器中填充完整图像

go - 如何使用两个客户端。使用golang

javascript - 在我的路由文件中传递函数/方法 react

javascript - Golang 请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 Origin 'null'

javascript - 如何获取所有浏览器cookie?

c# - 对 'var' 关键字和三元运算符有疑问? :

javascript - 一个有点痛苦的三重嵌套三元运算符

javascript - 文件上传触发两次?

javascript - javascript中的后缀树?