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

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

当前回答

可以直接使用相等运算符

<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确定变量是否未定义或为空

其他回答

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

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将为空。不会引发任何错误

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

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

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

return value == null; // also returns true if value is undefined
function isEmpty(obj) {
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
    else return !obj;
}

在ES6中,使用trim处理空白字符串:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}

这可能很有用。

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

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