Javascript 布尔等式

Javascript 布尔等式,javascript,boolean,logic,Javascript,Boolean,Logic,我是从一道试题中得出这个结论的,我不明白这个答案是怎么回事。如果值“x”和“y”相等,则该函数应返回“true”,否则返回False 解决方案: function equal_boolean (x , y) { return x ? y : y ? x : true; } 为什么这样做有效?据我所知,如果X是真的,它将被证明是在评估。如果X为真,它将返回Y。X如何被认为是“真的” 如果不是,它将评估Y是否为真,如果为真,它将返回X,如果不是,它将返回真 我的理解有什么问题吗?您应该做的第一

我是从一道试题中得出这个结论的,我不明白这个答案是怎么回事。如果值“x”和“y”相等,则该函数应返回“true”,否则返回False

解决方案:

function equal_boolean (x , y) {
  return x ? y : y ? x : true;
}
为什么这样做有效?据我所知,如果X是真的,它将被证明是在评估。如果X为真,它将返回Y。X如何被认为是“真的”

如果不是,它将评估Y是否为真,如果为真,它将返回X,如果不是,它将返回真


我的理解有什么问题吗?

您应该做的第一件事是将三元运算符组合在一起:

(x ? y : (y ? x : true))
  • 如果
    x
    true
    ,则返回
    y
    ,其值还告诉您
    x
    y
    是否相等
  • 如果
    x
    false
    ,则从第二个三值开始:
    • 如果
      y
      true
      ,则返回
      x
      false
      ),因为两者不相等
    • 如果
      y
      false
      ,则
      x
      y
      相等,因此返回
      true
解析为

if x
   return y       // if y is true, then x == y. if y is false, then x != y
else (x is false)
   if y
      return x    // x is false and y is true, y != x, return false
   else
      return true // x is false and y is false, return true
这当然是一种非常复杂的表示布尔等式的方法(aka aka
iff
)。更自然的说法是这样的:

 (x && y) || (!x && !y)

让我们试着扩展一下:

var myBool = x ? y : (y ? x : true)

return myBool;
第一街区

x ? y : ...
如果X为真,则返回Y的值。如果Y恰好为真,则两者相等。否则返回false(不匹配)

如果X为false,则第二个块:

y ? x : true
如果Y为true,则返回X.X为false,因此返回false(不匹配) 如果Y为false,则返回true-两个值都为false。

  • 首先确定表达式

    return x ? y : y ? x : true;
    //turns into
    return x ? y : (y ? x : true);
    
  • ?:
    三元运算符替换为
    if
    语句

    if (x) {
        return y;
    } else {
        //here x is false, so we will be able to replace x by false in the next step
        if (y) {
            return x;
        } else {
            return true;
        }
    }
    
  • 使
    语句更加详细,将
    返回x
    替换为
    返回false

    if (x == true) {
        return y;
    } else {
        if (y == true) {
            return false;
        } else {
            return true;
        }
    }
    
  • 最后替换
    返回y
    ,则通过
    进行编码,并检查所有可能性

    if (x == true) {
        if (y == true) {
            return true; // x == true and y == true
        } else {
            return false; // x == true and y == false
        }
    } else {
        if (y == true) {
            return false; // x == false and y == true
        } else {
            return true; // x == false and y == false
        }
    }
    

它起作用了。(只要x和y是布尔值)

只要:
返回x==y
@dfsq他的问题是为了理解一个练习,而不是如何提高效率。这里需要知道的重要一点是,在javascript的条件表达式中(例如在三元组的第一部分中),独立引用或文本隐式转换为布尔值。三元然后更明确地读取
!!x?y:!!Yx:对。但正如您在这里看到的,这不是一个有效的相等性测试:(返回类型既不总是布尔值,也不是正确的结果)。比我的要好得多(……:)谢谢!这个真的很有帮助!:D
if (x == true) {
    if (y == true) {
        return true; // x == true and y == true
    } else {
        return false; // x == true and y == false
    }
} else {
    if (y == true) {
        return false; // x == false and y == true
    } else {
        return true; // x == false and y == false
    }
}