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

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

当前回答

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

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

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

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

其他回答

这里是我的-如果值为null、undefined等或空白(即仅包含空格),则返回true:

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}

我认为使用?操作员稍微干净一点。

var ? function_if_exists() : function_if_doesnt_exist();

我非常喜欢的解决方案:

让我们定义一个空变量为空或未定义,或者如果它有长度,它为零,或者如果是一个对象,它没有键:

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}

可以直接使用相等运算符

<script>
    var firstName;
    var lastName = null;
    /* Since null == undefined is true, the following statements will catch both null and undefined */
        if(firstName == null){
            alert('Variable "firstName" is undefined.');
        }    
        if(lastName == null){
           alert('Variable "lastName" is null.');
        }
</script>

demo@如何使用JavaScript确定变量是否未定义或为空

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