JavaScript型別轉換:(true \u0026\u0026 1)vs(true | | 1)
JavaScript是非嚴格型別的Java語言,例如.
我們知道,它會根據上下文來轉換結果的值:
“2”“3”結果“23”
“2”*“3”結果6
這是非常明確的,可以理解.
我只是嘗試了以下表達式,並被困惑:
真實&& 1結果1
真|| 1個結果是真的
為什麼第一個給數字和第二個給出布林值?
考慮到JavaScript轉換規則,我希望在這兩種情況下都會得到布林值,因為表示式的布林上下文.
The && operator is commonly called logical and. It can also be calledguard. If the first operand is false, null, undefined, “” (the emptystring), or the number 0 then it returns the first operand. Otherwise,it returns the second operand. This provides a convenient way to writea null-check:
var value = p && p.name; /* The name value will only be retrieved from p if p has a value, avoiding an error. */
The || operator is commonlycalled logical or. It can also be called default. If the first operandis false, null, undefined, “” (the empty string), or the number 0,then it returns the second operand. Otherwise, it returns the firstoperand. This provides a convenient way to specify default values:
value = v || 10; /* Use the value of v, but if v doesn't have a value, use 10 instead. */
http://stackoverflow.com/questions/8559920/javascript-type-conversion-true-1-vs-true-1