是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
当前回答
此函数检查空对象{}、空数组[]、空、未定义和空字符串“”
function isEmpty(val) {
//check for empty object {}, array []
if (val !== null && typeof val === 'object') {
if (Object.keys(obj).length === 0) {
return true;
}
}
//check for undefined, null and ""
else if (val == null || val === "") {
return true;
}
return false;
}
var val={};isEmpty(val)->trueval=[];isEmpty(val)->trueisEmpty(未定义)->trueisEmpty(null)->trueisEmpty(“”)->trueisEmpty(false)->falseisEmpty(0)->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确定变量是否未定义或为空
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 a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true
检查变量是否未定义或为空
var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false
你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。
这可能很有用。
数组中的所有值都表示您想要的值(空值、未定义值或其他值),您可以在其中搜索所需的值。
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1