是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
当前回答
您可以只检查变量是否具有真实值。这意味着
if (value) {
// do something..
}
如果值不是:
无效的未定义NaN公司空字符串(“”)0假的
上面的列表表示ECMA-/Javascript中所有可能的错误值。在ToBoolean部分的规范中找到它。
此外,如果您不知道变量是否存在(也就是说,如果声明了变量),则应使用typeof运算符进行检查。例如
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
如果您可以确定至少声明了一个变量,那么应该直接检查它是否具有如上所示的真实值。
其他回答
检查值是否未定义或为空的详细方法为:
return value === undefined || value === null;
您也可以使用==运算符,但这需要您了解所有规则:
return value == null; // also returns true if value is undefined
function isEmpty(value){
return (value == null || value.length === 0);
}
对于
undefined // Because undefined == null
null
[]
""
和零参数函数,因为函数的长度是它所使用的声明参数的数量。
要禁止后一个类别,您可能只需要检查空白字符串
function isEmpty(value){
return (value == null || value === '');
}
Null或空白
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
这可能很有用。
数组中的所有值都表示您想要的值(空值、未定义值或其他值),您可以在其中搜索所需的值。
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
我认为使用?操作员稍微干净一点。
var ? function_if_exists() : function_if_doesnt_exist();
看看新的ECMAScript Nullish合并运算符
你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。
let x = foo ?? bar();
同样,上述代码与以下代码等效。
let x = (foo !== null && foo !== undefined) ? foo : bar();