0

今日、条件のロギングとテストを試みているときに、Chome コンソールで次のシナリオに出くわしました。誰かがなぜこの振る舞いを正確に理解するのを手伝ってくれますか?

// 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
4

3 に答える 3

3

問題は演算子の優先順位にあります。「プラス」演算子 (+) は > より優先度が高くなります。

したがって、最初のログは次のように解釈されます。

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

最初のステップで、JS インターピーターは文字列と「100」を連結します。

詳細については、このMDN 記事を参照してください。

于 2013-03-05T13:16:39.073 に答える
0

これは正常な動作です。

1) 評価するとき

"this is not good = " + 100 > 0

あなたは評価します:

"this is not good = 100" > 0

明らかにfalsefalse印刷されます。

2) 評価するとき

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

あなたが評価します

"this is not good = " + true

文字列を出力するだけです。

おまけ) の場合undefined、これは の戻り値ですconsole.log()。常にundefinedこの機能のためです。

于 2013-03-05T13:22:58.070 に答える
0

Javascript は指定した順序で操作を実行しているためです。

"this is not good = " + 100

結果として

this is not good = 100

その後

"this is not good = + 100" > 0

String は 0 より大きくないため、false になります。


フローでは、最初の変数は文字列であり、+(加算演算子) は 2 つの文字列を連結しようとします。次に100、キャストされ"100"て追加されます。

代わりに括弧を使用すると、数学演算が実行され (最初の変数が100, になるため)、結果falseが返され、文字列にキャストさ"false"れてから、最初の文字列変数に追加されます。

于 2013-03-05T13:27:08.490 に答える