有人能解释一下为什么在Javascript中,
alert({} == true)
显示 false
if ({}) alert('true')
显示 true?
在if条件中有什么不同会改变结果?
我想写一些简写参数验证器 obj || (obj = {});
,但我对这个发现感到困惑。
有人能解释一下为什么在Javascript中,
alert({} == true)
显示 false
if ({}) alert('true')
显示 true?
在if条件中有什么不同会改变结果?
我想写一些简写参数验证器 obj || (obj = {});
,但我对这个发现感到困惑。
if ({}) alert('true')
-> true
{}
是一个对象,在if
语句的上下文中被求值时,会被强制转换为一个Boolean
值,由于Boolean({})
的结果为true
,因此得到了if (true)
。这在ECMAScript规范的第12.5节 if语句中有所记录:
The production If Statement : if ( Expression ) Statement is evaluated as follows:
- Let exprRef be the result of evaluating Expression.
- If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
- Return the result of evaluating Statement.
alert({} == true)
-> false
因此,比较x == y,其中x和y是值,产生true或false。 这样的比较执行如下:
如果Type(y)是布尔类型,则返回比较结果x == ToNumber(y)。
{} == true
将被评估为{} == Number(true)
,这被评估为{} == 1
,即false
。1 == true
评估为true
,但2 == true
评估为false
的原因。{}
不是 true
,所以它不会在你的第一个示例中显示。在你的第二个示例中,{}
不是 false,因此它将通过测试。
就像我的老师曾经说过的那样,你不能比较土豆和胡萝卜。
这不仅适用于数组,还适用于任何东西:
alert(3 == true); // shows false
if (3) alert('true'); // shows true
if(exp) statement
实际上是指 '如果 exp 不为假,则执行 exp'? - Cristi Mihainull
或 undefined
。或者 1
会被解释为 true
,因为它可以转换为布尔类型的 true
。 - Tchoupi在布尔运算中,通常任何不为0
的值都会被视为真。
http://jsfiddle.net/QF8GW/
if (0) console.log("0 shows true"); // does not log a value
if (-1) console.log("-1 shows true");
if (12345) console.log("12345 shows true");
if ({}) console.log("{} shows true");
if ([]) console.log("[] shows true");
除了0
以外,所有这些内容都将被评估为true。
然而,与true
进行比较时,它们的值不会被评估为true
。
// logs the statement (1 and true are the same.)
if (1 == true) console.log("1==true shows true");
if (12345 == true) console.log("12345==true shows true"); // does not log
alert({} == true) //display "false"
if({} == true)
{
alert("it's true");
}else
{
alert("it's false"); // <-- alert this
}
alert('true')
的显示。 - Tchoupitrue
。 - Pointyif({})
等价于if ({} != false)
,而不是if ({} == true)
。这会让你获得一个奇怪的结果,见http://jsfiddle.net/kq8QL/1/。 - mellamokb(obj || (obj = {})
会导致ReferenceError
错误。请使用(obj || {})
,或者(obj || (obj={},obj))
。那这和你的问题有什么关系呢? - KooiInc