是否有标准函数来检查JavaScript中的null,undefined或blank变量? [英] Is there a standard function to check for null, undefined, or blank variables in JavaScript?
问题描述
是否存在通用JavaScript函数,用于检查变量是否具有值并确保它不是 undefined
或 null
?我有这个代码,但我不确定它是否涵盖所有情况:
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined
or null
? I've got this code, but I'm not sure if it covers all cases:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
推荐答案
你可以检查一下变量是否具有 truthy
值。这意味着
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
将评估为 true
如果值
为不:
- null
- undefined
- NaN
- 空字符串()
- 0
- false
- null
- undefined
- NaN
- empty string ("")
- 0
- false
上面的列表代表了ECMA- / Javascript中所有可能的 falsy
值。在规范中找到 ToBoolean
section。
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specification at the ToBoolean
section.
此外,如果你不知道是否存在变量(这意味着,如果它是声明),你应该检查 typeof
运算符。例如
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
如果可以确定变量至少声明,你应该直接检查它是否有如上所示的 truthy
值。
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
进一步阅读: http://typeofnan.blogspot.com/2011/01/typeof-is -fast.html
这篇关于是否有标准函数来检查JavaScript中的null,undefined或blank变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!