在JS中是(a==b==c)和((a=+=b)&&(a==c)&&(b==c))相同//对不

in JS, are (a===b===c) and ( (a===b)&&(a===c)&&(b===c) ) the same? //sorry for my ignorance

本文关键字:amp 相同 对不 JS 中是      更新时间:2023-11-18

我的目标是"在只有a、b和c相等的情况下执行代码"。我算出了两个代码:

代码#1:

if (a===b===c) {console.log('something')};

代码#2:

if ( (a===b)&&(a===c)&&(b===c) ) {console.log('something')};

我尝试了这两种方法,并意识到只有"代码#2"才能响应我的目的(仅在3个变量相等时执行(例如a=b=c),但对于"代码#1",只要有2个等效变量(例如a=bb=c.),它就会执行

我的问题是:"代码#1和代码#2之间有什么区别?"

您实际要问的问题是这两者是否相同:

if (a === b === c) {...}
if ((a === b) && (b === c) && (a === c)) {...}

很快,他们就不是了。第一种可以概括为:

if ((a === b) === c) {...}

如果a和b相等,则评估为

if (true === c) {...}

这与检查三者是否相等不同
要检查三种方式的相等性,您必须手动检查所有方面:

if ((a === b) && (b === c)) {...}  

我将尝试解释其中的区别。解释第一个代码示例:

if (a=b=c) {console.log('something')};
// Code above means: if (c) {console.log('something')};
// So if Boolean(c) is false, console.log will not work

解释第二个例子:

if ( (a=b)&&(a=c)&&(b=c) ) {console.log('something')};
// Code above means: if (b && c && c) {console.log('something')};
// So if Boolean(c) or Boolean(b) is false, console.log will not work

赋值运算符根据其右操作数的值为其左操作数赋值,并返回其右操作数值。

真值表的时间。。。最后两列是您正在比较的表达式

A       | B     | C     | A == B    | (A == B) == C | A == B && B == C
--------+-------+-------+-----------+---------------+-----------------
TRUE    | TRUE  | TRUE  | TRUE      | TRUE          | TRUE
TRUE    | TRUE  | FALSE | TRUE      | FALSE         | FALSE
TRUE    | FALSE | TRUE  | FALSE     | FALSE         | FALSE
TRUE    | FALSE | FALSE | FALSE     | TRUE          | FALSE
FALSE   | TRUE  | TRUE  | FALSE     | FALSE         | FALSE
FALSE   | TRUE  | FALSE | FALSE     | TRUE          | FALSE
FALSE   | FALSE | TRUE  | TRUE      | TRUE          | FALSE
FALSE   | FALSE | FALSE | TRUE      | FALSE         | TRUE

不!它们不一样。