如果我将一个变量设置为 0,我会得到一个奇怪的行为,即与“”(空)的比较为真。如何检查变量是否真的为空?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
最佳答案
使用strict comparison operators
===
和 !==
使用 ==
和 !=
(称为抽象比较运算符),
If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.
如果为空,你想检查变量是否没有被定义,使用:
if (typeof tmp !== "undefined") {
// it exists!
}
关于javascript - 我如何与空变量进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16056476/