布尔相等

时间:2014-09-07 13:59:50

标签: javascript boolean logic

我从考试问题中得到了这个,并且无法理解解决方案的工作原理。这个函数应该返回" true"如果值" x"和" y"是相等的,否则返回False。

解决方案:

function equal_boolean (x , y) {
  return x ? y : y ? x : true;
}

为什么这样做?根据我的理解,最终会评估X是否为真。如果X为真,它将返回Y. X应该如何" true"?

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

我的理解是否有问题?

4 个答案:

答案 0 :(得分:4)

return x ? y : y ? x : 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

这当然是表达布尔相等性的一种非常复杂的方式(又名Logical biconditional又名iff)。更自然的是这样的表达:

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

答案 1 :(得分:3)

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

(x ? y : (y ? x : true))
  • 如果xtrue,则返回y,其值也会告诉您xy是否相等
  • 如果xfalse,则从第二个三元开始:
    • 如果ytrue,则返回xfalse),因为两者不相等
    • 如果yfalse,则xy相等,请返回true

答案 2 :(得分:0)

让我们尝试扩展一下:

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

return myBool;

第一块

x ? y : ...

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

如果X为假,则为第二块:

y ? x : true

如果Y为真,则返回X.X为假,因此返回false(不匹配) 如果Y为false,则返回true - 两个值均为false。

答案 3 :(得分:0)

  • 首先确定表达式

    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;
        }
    }
    
  • 使if语句更加详细,将return x替换为return false

    if (x == true) {
        return y;
    } else {
        if (y == true) {
            return false;
        } else {
            return true;
        }
    }
    
  • 最后将return y;替换为if (y == true) { return true; } else { return false; },并检查所有可能性

    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是布尔值)