JavaScript 中的 null 或未定义检查

null or undefined check in javascript

本文关键字:未定义 检查 null 中的 JavaScript      更新时间:2023-09-26

我在localStorage中缓存了一个字符串

 checkLoop:function(){   //function is hit only if internet is connected
 localStorage['key'] = "Some string response from web service";
 //JSON Web service could return null, "" (empty response) too
 }

仅当有互联网连接时,才会定义此密钥。因此,我的功能checkLoop有可能从未被击中。即从未定义本地存储。

稍后我检查一下,看看它是defined还是null

所以像if(!localStorage['key']){..//TODO..}这样的支票会起作用吗?

或者我需要对其进行更多自定义以获得更好的代码?

if(!localStorage['key']){
    // Will enter if the value is null'undefined'false'0'""
}

您可能希望改用以下内容:

if(localStorage['key'] == null){
    // only null'undefined.
}

演示

JavaScript 中的 falsy 值是:

  • 定义
  • 0
  • " - (空字符串)

使用 typeof

if(typeof localStorage['key'] !== 'undefined'){ 
    // Do Something 
}

注意:如果要存储false0值,这将非常有用。