【问题标题】:Call a function only if a value is neither null nor undefined仅当值既不是 null 也不是 undefined 时才调用函数
【发布时间】:2012-04-11 22:57:34
【问题描述】:

单击按钮时,我会检查本地存储键中是否存在某些内容:

var a = localStorage.getItem('foo');
if (typeof a != 'undefined') {
    // Function
}

但如果该键根本不存在,则返回 null。我如何调用如果不是未定义且不为空做函数,否则返回 true(?) 或继续?

【问题讨论】:

    标签: jquery null local-storage undefined


    【解决方案1】:

    如果 false0NaN 或空字符串是 localStorage 中的有效值,则不应使用 JavaScript 的虚假比较。

    您应该检查项目是否等于null 或等于undefined

    var a = localStorage.getItem('foo');
    if (a === null || a === undefined) {
        // Function
    }
    

    请注意,三等号 (===) 运算符会进行精确比较,而没有 type coercion。使用双等号 (==) 运算符可以应用一组特殊的规则来隐藏相似但类型不同的值。其中最有用的一个是null == undefined,可以简化上面的代码:

    var a = localStorage.getItem('foo');
    if (a != null) {
        // Function
    }
    

    如果 a 是 nullundefined,则里面的代码将不会运行。

    【讨论】:

      【解决方案2】:

      JavaScript 有一个 falsy 值的概念...即 0、nullundefined 和一个空字符串。

      因此,您应该能够通过以下方式检查 a 是否“真实”(即不是我上面提到的值之一):

      var a = localStorage.getItem('foo');
      if (a) {
          // Function
      }
      

      更多信息from SitePoint available here

      【讨论】:

        猜你喜欢
        • 2018-01-28
        • 1970-01-01
        • 2021-07-05
        • 1970-01-01
        • 2015-09-16
        • 1970-01-01
        相关资源
        最近更新 更多