是否有一个通用的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;
}
当前回答
如果您正在使用TypeScript,并且不想考虑“值为假”,那么这就是您的解决方案:
首先:从“util”导入{isNullOrUndefined};
然后:isNullOrUndefined(this.yourVariableName)
请注意:如下文所述,现在已弃用此选项,请改用value==undefined||value==null。裁判。
其他回答
看看新的ECMAScript Nullish合并运算符
你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。
let x = foo ?? bar();
同样,上述代码与以下代码等效。
let x = (foo !== null && foo !== undefined) ? foo : bar();
我非常喜欢的解决方案:
让我们定义一个空变量为空或未定义,或者如果它有长度,它为零,或者如果是一个对象,它没有键:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
退货:
true:undefined,null,“”,[],{}false:true,false,1,0,-1,“foo”,[1,2,3],{foo:1}
你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。
try{
let vari = obj.propTest; // obj may be don't have propTest property
...
} catch(NullException){
// do something here
}
我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。
仅使用“空值合并”检查未定义和空值
if ((myVariable ?? undefined) !== undefined) {
// handle myVariable has a value, including 0 or ""
}
else {
// handle undefined or null only
}
来自铬控制台
{const x=undefined; (x ?? undefined) !== undefined}
false
{const x=null; (x ?? undefined) !== undefined}
false
{const x=0; (x ?? undefined) !== undefined}
true
{const x=""; (x ?? undefined) !== undefined}
true
{const x={}; (x ?? undefined) !== undefined}
true
{const x=[]; (x ?? undefined) !== undefined}
true
{const x="a"; (x ?? undefined) !== undefined}
true