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

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

当前回答

如果您正在使用TypeScript,并且不想考虑“值为假”,那么这就是您的解决方案:

首先:从“util”导入{isNullOrUndefined};

然后:isNullOrUndefined(this.yourVariableName)

请注意:如下文所述,现在已弃用此选项,请改用value==undefined||value==null。裁判。

其他回答

这可能很有用。

数组中的所有值都表示您想要的值(空值、未定义值或其他值),您可以在其中搜索所需的值。

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1

检查值是否未定义或为空的详细方法为:

return value === undefined || value === null;

您也可以使用==运算符,但这需要您了解所有规则:

return value == null; // also returns true if value is undefined

你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。

function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

它还将检查空格(“”)以及以下内容:

null,未定义,NaN,空,字符串(“”),0,false

您可以始终使用loadash函数,例如_.isNil或_.isUndefined。它们非常容易使用。