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, undefinedfalsetrue.
true||
如果第一个值是 法尔西
,它回来了 第二值.
如果第一个值是 特鲁西
,它回来了 第一值.
||
function or(x, y) {
if (x) {
return x;
} else {
return y;
}}xxif
(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.".
xeitherXorYy"Either x or y is truthy."y"Neither x nor y is truthy".
实际问题
||x = x || yxxxyxundefinednull
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));}falseflagAtruefalse)? true.flagAfalse.
flagAundefined
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;
foodefault
var foobar = foo || bar || something || 42;
添加回答
举报
