仅在值既不为null也未定义时调用函数

时间:2012-03-28 10:54:40

标签: jquery null local-storage undefined

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

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

但是如果密钥根本不存在,则返回null。我如何调用如果没有未定义而不是null执行函数,否则返回true(?)或继续?

2 个答案:

答案 0 :(得分:3)

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

因此,你应该能够检查a是否是“真实的”(即我上面提到的值之一),通过这样做:

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

更多信息from SitePoint available here

答案 1 :(得分:0)

如果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,则内部代码将无法运行。