仅当值既不是null也不是undefined时才调用函数 [英] Call a function only if a value is neither null nor undefined
问题描述
单击按钮时,我检查本地存储密钥中是否存在某些内容,例如:
var a = localStorage.getItem('foo');
if (typeof a != 'undefined') {
// Function
}
,但如果键根本不存在,则返回null.我该如何呼叫如果不是未定义且不为null的函数,否则返回true(?)或继续吗?
JavaScript具有 falsy 值的概念,即0,null
,undefined
和空字符串. /p>
因此,您应该可以通过执行以下操作来检查a
是否真实"(即不是我上面提到的值之一):
var a = localStorage.getItem('foo');
if (a) {
// Function
}
更多信息来自SitePoint,可在此处
When a button is clicked I check if something exists in a localstorage key as such:
var a = localStorage.getItem('foo');
if (typeof a != 'undefined') {
// Function
}
but if the key doesn't exists at all, it return null. How can I call if not undefined and not null do function, else return true(?) or continue?
JavaScript has a concept of falsy values... i.e. 0, null
, undefined
and an empty string.
Because of this, you should be able to just check if a
is "truthy" (i.e. not one of the values I've mentioned above), by doing this:
var a = localStorage.getItem('foo');
if (a) {
// Function
}
More information from SitePoint available here
这篇关于仅当值既不是null也不是undefined时才调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!