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

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

当前回答

看看新的ECMAScript Nullish合并运算符

你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。

let x = foo ?? bar();

同样,上述代码与以下代码等效。

let x = (foo !== null && foo !== undefined) ? foo : bar();

其他回答

第一个评分最好的答案是错误的。若值未定义,则会在现代浏览器中引发异常。您必须使用:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)
function isEmpty(val){
    return !val;
}

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

if(!val)...

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

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 variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1

看看新的ECMAScript Nullish合并运算符

你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。

let x = foo ?? bar();

同样,上述代码与以下代码等效。

let x = (foo !== null && foo !== undefined) ? foo : bar();