3 回答

TA貢獻1951條經驗 獲得超3個贊
什么是雙管操作符( ||
)?
||
OR
如果第一個值是 false
,它檢查第二個值。如果是 true
,它回來了 true
如果是 false
,它回來了 false
.如果第一個值是 true
,它總是會回來 true
無論第二個值是什么。
function or(x, y) { if (x) { return true; } else if (y) { return true; } else { return false; }}
| true false ------+---------------true | true true false | true false
它在JavaScript中有何不同?
||
(function(){}) || {}
0
, ""
, null
, undefined
false
true
.
true
||
如果第一個值是 法爾西
,它回來了 第二值.
如果第一個值是 特魯西
,它回來了 第一值.
||
function or(x, y) { if (x) { return x; } else { return y; }}
x
x
if
(function(x, y) { var eitherXorY = x || y; if (eitherXorY) { console.log("Either x or y is truthy."); } else { console.log("Neither x nor y is truthy"); }}(true/*, undefined*/));
"Either x or y is truthy."
.
x
eitherXorY
y
"Either x or y is truthy."
y
"Neither x nor y is truthy"
.
實際問題
||
x = x || y
x
x
x
y
x
undefined
null
function badFunction(/* boolean */flagA) { flagA = flagA || true; console.log("flagA is set to " + (flagA ? "true" : "false"));}
false
flagA
true
false
)? true
.flagA
false
.
flagA
undefined
function goodFunction(/* boolean */flagA) { flagA = typeof flagA !== "undefined" ? flagA : true; console.log("flagA is set to " + (flagA ? "true" : "false"));}

TA貢獻1821條經驗 獲得超5個贊
var foobar = foo || default;
foo
default
var foobar = foo || bar || something || 42;
添加回答
舉報