为什么 JavaScript 空值检查不起作用?

Why JavaScript null check doesn't working?

function readProperty(property)
{
  console.log(localStorage[property]) //Alerts “null”
  if(localStorage[property] == null)
  {
      console.log('Null chek')
      return false;
  }

  return localStorage[property];
}

log 输出“null”,但 'if()' 不起作用。我尝试使用 ===,它也不起作用。请帮忙

UPD:谢谢大家,这个改变帮助了我 if(localStorage[property] == 'null')

虽然:console.log(localStorage[property])可能会报null,但实际值为undefined

因此,在您的 if 语句中,如果您针对 undefined 进行测试,您将获得匹配项。

更好的是,只需使用以下方法测试值是否存在:

 if(localStorage[property])...  // Tests for any "truthy" value

 if(!localStorage[property])...  // Tests for any "falsey" value

你必须像那样使用 getItem() 函数从 localStorage 获取项目

if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
   // there is no item in localStorage with the property name 
}

The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

尝试:

localStorage[property] === 'null'

嗯,我不知道你是想使用全局变量 localStorage 还是你代码中定义的变量。

如果您正在使用 localStorage API,您应该检查是否存在这样的密钥...

if (!localStorage.getItem("my-item")) {
  console.log("item doesn't exist.");
}

.getItem() 方法 returns null 未定义密钥时,因此使用 !item !== null 进行检查。

.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.