问题
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?
回答1:
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
回答2:
You should not use JavaScript's falsy comparisons if false
, 0
, NaN
, or the empty string are valid values in your localStorage.
Instead you should check if the item is equal to null
or is equal to undefined
:
var a = localStorage.getItem('foo');
if (a === null || a === undefined) {
// Function
}
Note that the triple equals (===
) operator compares exactly, without type coercion. Using double equals (==
) operator a special set of rules are applied to covert similar values but of different types. One of the most useful of these is that null == undefined
, allowing simplification the above code:
var a = localStorage.getItem('foo');
if (a != null) {
// Function
}
If a is null
or undefined
the code inside will not run.
来源:https://stackoverflow.com/questions/9906009/call-a-function-only-if-a-value-is-neither-null-nor-undefined