是否有标准函数来检查 JavaScript 中的 null、未定义或空白变量? [英] 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 ) {
}
如果 value
是 not,
将评估为 true
:
- 空
- 未定义
- NaN
- 空字符串(")
- 0
- 假
上面的列表代表了 ECMA-/Javascript 中所有可能的 falsy
值.在ToBoolean规范中找到它/code> 部分.
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.
这篇关于是否有标准函数来检查 JavaScript 中的 null、未定义或空白变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!