如何确定变量是未定义的还是空的?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但如果我这样做,JavaScript解释器将停止执行。
如何确定变量是未定义的还是空的?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但如果我这样做,JavaScript解释器将停止执行。
当前回答
如果创建一个函数来检查它:
export function isEmpty (v) {
if (typeof v === "undefined") {
return true;
}
if (v === null) {
return true;
}
if (typeof v === "object" && Object.keys(v).length === 0) {
return true;
}
if (Array.isArray(v) && v.length === 0) {
return true;
}
if (typeof v === "string" && v.trim().length === 0) {
return true;
}
return false;
}
其他回答
我在Chrome控制台上运行这个测试。使用(void 0)可以检查undefined:
var c;
undefined
if (c === void 0) alert();
// output = undefined
var c = 1;
// output = undefined
if (c === void 0) alert();
// output = undefined
// check c value c
// output = 1
if (c === void 0) alert();
// output = undefined
c = undefined;
// output = undefined
if (c === void 0) alert();
// output = undefined
编辑后的答案:在我看来,你不应该使用我下面的旧答案中的函数。相反,您应该知道变量的类型,并直接使用根据检查(例如,想知道数组是否为空?只需执行if(arr.length==0){}等)。这个答案甚至不能回答OP的问题。
我来编写自己的函数。JavaScript很奇怪。
它几乎可以用于任何事情。(注意,这也会检查变量是否包含任何可用值。但由于通常也需要这些信息,我认为值得发布)。请考虑留下一张纸条。
function empty(v) {
let type = typeof v;
if (type === 'undefined') {
return true;
}
if (type === 'boolean') {
return !v;
}
if (v === null) {
return true;
}
if (v === undefined) {
return true;
}
if (v instanceof Array) {
if (v.length < 1) {
return true;
}
} else if (type === 'string') {
if (v.length < 1) {
return true;
}
if (v === '0') {
return true;
}
} else if (type === 'object') {
if (Object.keys(v).length < 1) {
return true;
}
} else if (type === 'number') {
if (v === 0) {
return true;
}
}
return false;
}
TypeScript兼容。
该函数应该执行与PHP的empty()函数完全相同的操作(请参见RETURN VALUES)
将undefined、null、false、0、0.0、“0”{}、[]视为空。
“0.0”、NaN、“”、true被视为非空。
if (typeof EmpName != 'undefined' && EmpName) {
如果值不是:
无效的未定义NaN公司空字符串(“”)0假的
你可以这样做,我认为在一个条件下对同一变量进行多值检查更有效
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
最简单的答案:
if(!EmpName){
// DO SOMETHING
};