如果我将一个变量设置为0,那么与“”(空)进行比较时会出现奇怪的行为,返回true。如何检查变量是否真正为空?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
如果我将一个变量设置为0,那么与“”(空)进行比较时会出现奇怪的行为,返回true。如何检查变量是否真正为空?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
使用严格比较运算符===
和!==
使用==
和!=
(称为抽象比较运算符),
如果两个操作数的类型不同,JavaScript会尝试将操作数转换为适当的类型进行比较。
if (typeof tmp !== "undefined") {
// it exists!
}
0
、NaN
、undefined
、false
和null
之外的所有内容都被视为false。""被视为true
。if (tmp) {
}
如果变量包含除了 0
, NaN
, undefined
, false
和 null
之外的任何值,则会执行上述 if
语句。
如果 tmp
是一个 string
,则可以使用以下代码:
if (tmp !== "") {
}
===
和!==
运算符在比较时不进行类型转换。
if (tmp !== "")
JavaScript会隐式地将值转换为其他类型。如果要检查类型,可以使用!==
运算符:
if ( tmp !== "")
if(!tmp)
或者if ( tmp !== "")
应该可以工作。 - Breezertmp!==undefined
- ShuklaSannidhya