console.log()没有使用括号()返回逻辑测试

时间:2013-03-05 13:13:28

标签: javascript undefined-behavior

今天在尝试记录和测试条件时,我遇到了Chrome控制台的以下场景。有人可以帮助我理解为什么会出现这种行为。

// 1. in this output "this is not good" is not there and returned is false then 
// undefined ?? is that returned value
console.log("this is not good = " + 100 > 0 )
false
undefined
// 2. next case is executing fine by introducing ()... 
// undefined ?? return type
console.log("this is not good = " + (100 > 0) )
this is not good = true
undefined

3 个答案:

答案 0 :(得分:3)

问题在于运营商优先级。 'Plus'运算符(+)的优先级高于&gt ;.

所以你的第一个日志解释如下:

console.log((this is not good = " + 100) > 0);

在第一步中,JS interpeter将连接字符串和“100”。

有关详细信息,请参阅此MDN article

答案 1 :(得分:0)

这是正常行为。

1)评估时

"this is not good = " + 100 > 0

您将评估:

"this is not good = 100" > 0

显然是false,因此会打印false

2)评估时

"this is not good = " + (100 > 0)

你将评估

"this is not good = " + true

它只会打印字符串。

Bonus)对于undefined,这是console.log()的返回值。这个函数总是undefined

答案 2 :(得分:0)

因为Javascript按照您指定的顺序执行操作。

"this is not good = " + 100

将导致

this is not good = 100

然后

"this is not good = + 100" > 0

将为false,因为String不大于零。


在你的流程中,第一个变量是一个String,+(加法运算符)将尝试连接两个字符串。然后100将投放"100"并添加。

如果使用括号,则将执行数学运算(因为第一个变量将是100,一个数字),结果false将被返回,转换为字符串{{1然后添加到您的第一个String变量。