单击按钮时,我会检查localstorage键中是否存在某些内容:
var a = localStorage.getItem('foo');
if (typeof a != 'undefined') {
// Function
}
但是如果密钥根本不存在,则返回null。我如何调用如果没有未定义而不是null执行函数,否则返回true(?)或继续?
答案 0 :(得分:3)
JavaScript有 falsy 值的概念......即0,null
,undefined
和空字符串。
因此,你应该能够检查a
是否是“真实的”(即我上面提到的值之一),通过这样做:
var a = localStorage.getItem('foo');
if (a) {
// Function
}
答案 1 :(得分:0)
如果false
,0
,NaN
或空字符串是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为null
或undefined
,则内部代码将无法运行。