如何确定变量是未定义的还是空的?

我的代码如下:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

但如果我这样做,JavaScript解释器将停止执行。


当前回答

最短最简单的:

if(!EmpName ){
 // DO SOMETHING
}

如果EmpName为:

无效的未定义NaN公司空的字符串(“”)0假的

其他回答

我刚刚遇到了这个问题,即检查对象是否为空。我只使用这个:

if (object) {
    // Your code
}

例如:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

最简单的检查方法是:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}

使用以下解决方案:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

我可以检查以下内容:

无效的未定义NaN公司空的字符串(“”)0假的

编辑后的答案:在我看来,你不应该使用我下面的旧答案中的函数。相反,您应该知道变量的类型,并直接使用根据检查(例如,想知道数组是否为空?只需执行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被视为非空。

(null == undefined)  // true

(null === undefined) // false

因为==检查类型和值。两者的类型不同,但值相同。