是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

当前回答

仅使用“空值合并”检查未定义和空值

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

其他回答

var myNewValue = myObject && myObject.child && myObject.child.myValue;

这永远不会抛出错误。如果myObject、child或myValue为空,则myNewValue将为空。不会引发任何错误

对于我的案例,我尝试了if null,“”!变量,但它不起作用。

查看下面的代码以从html字段获取文本

var status=$(this).text(); //for example (for my case)

如果状态变量中没有值(没有文本),我试图将值“novalue”设置为状态变量。

以下代码有效。

if(status == false)
{
   status='novalue';
} 

当没有找到satus变量的文本时,上面的代码将“novalue”分配给状态变量

function isEmpty(val){
    return !val;
}

但是这个解决方案是过度设计的,如果您不想稍后根据业务模型的需要修改函数,那么直接在代码中使用它会更干净:

if(!val)...

可以使用参数成为数组的参数滤器

函数validateAttributes(arg1、arg2、arg3、arg4){var args=对象.values(参数);return(args.filter(x=>x===null||!x))。长度<=0}console.log(validateAttributes('1',2,3,4));console.log(validateAttributes('1',2,3,null));console.log(validateAttributes('1',未定义,3,4));console.log(validateAttributes('1',2,'',4));console.log(validateAttributes('1',2,3,null));

如果变量尚未声明,则无法使用函数测试未定义,因为会出现错误。

if (foo) {}
function (bar) {}(foo)

如果尚未声明foo,则两者都将生成错误。

如果要测试变量是否已声明,可以使用

typeof foo != "undefined"

如果您想测试foo是否已声明,并且它有一个值,您可以使用

if (typeof foo != "undefined" && foo) {
    //code here
}