仅当值既不是null也不是undefined时才调用函数 [英] Call a function only if a value is neither null nor undefined

查看:151
本文介绍了仅当值既不是null也不是undefined时才调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮时,我检查本地存储密钥中是否存在某些内容,例如:

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

,但如果键根本不存在,则返回null.我该如何呼叫如果不是未定义且不为null的函数,否则返回true(?)或继续吗?

解决方案

JavaScript具有 falsy 值的概念,即0,nullundefined和空字符串. /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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆