Javascript Can';无法正确检查现有cookie

Javascript Can';无法正确检查现有cookie,javascript,if-statement,cookies,Javascript,If Statement,Cookies,我错过了一些非常简单的事情 我有一个设置cookie的按钮: <button id="gotit" >Got it</button> 我使用一个带有简单if-else的checkGetIt()函数: function checkGetIt() { var gotIt = getCookie("gotIt"); if (gotIt === "") { console.log('no such cooki

我错过了一些非常简单的事情

我有一个设置cookie的按钮:

<button id="gotit" >Got it</button>
我使用一个带有简单if-else的
checkGetIt()
函数:

 function checkGetIt() {
          var gotIt = getCookie("gotIt");
          if (gotIt === "") {
              console.log('no such cookie'); // should do this until button pressed
          } else {
              console.log('cookie exists'); // this displays all the time, which is wrong
          }
      }
      checkGetIt();
      var z = document.cookie;
   console.log('existing cookies: ' + z);
但是我总是得到
console.log('cookie存在')即使
console.log('existingcookies:'+z)在单击按钮之前不给我任何信息

setCookie()和getCookie()是我以前使用过的通用函数


.

您在以下行中遇到问题:

if (gotIt === "")
将其更改为:

if (gotIt === null) // This will check for null.
或:

进一步阅读:


您应该始终使用“==”(无类型转换),除了检查“undefined or null”,在这种情况下,最好的方法是比较“==null”。

谢谢,这很有效。如果(cookie==“”)可以工作,但在某些情况下必须是(cookie===null),请您评论一下在什么情况下可以工作?
null
是指未设置cookie。有时可以将cookie设置为空字符串
”。您正在执行if(cookie==”),在英语中是“if the cookie variable is a empty string”,正如您在getCookie函数中看到的那样,返回null。因此,该条件将始终返回false。有关更多信息,请参阅我在答案中提供的链接。如果你还有疑问,请告诉我们。这就是原因。干杯
if (gotIt === null) // This will check for null.
if (gotIt == null) // This will check for null or undefined.