(A == B == C)比较在JavaScript中是如何工作的? [英] How does (A == B == C) comparison work in JavaScript?

查看:128
本文介绍了(A == B == C)比较在JavaScript中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望下面的比较给出一个错误:

  var A = B = 0; 
if(A == B == 0)
console.log(true);
else
console.log(false);

但奇怪的是它会返回 false p>

更奇怪的是,

  console.log == 1)); 

返回 true



这种三元比较是如何工作的?

解决方案

要理解一个数字和一个布尔值之间的 == 比较将导致布尔值的内部类型转换为一个数字( true 变为 1 false 变为 0



您显示的表达式是从左到右计算的。因此,首先

  A == B 

并且结果为 true ,并且您正在将 true 与0 。由于 true 在比较期间变为 1 ,所以 1 == 0 计算结果为 false 。但是当你说

  console.log((A == B == 1)); 

A == B $ c> true ,当与数字比较时,变成 1 ,您再次与1进行比较。这就是为什么它打印 true


I was expecting the following comparison to give an error:

var A = B = 0;
if(A == B == 0)
    console.log(true);
else
    console.log(false);

but strangely it returns false.

Even more strangely,

console.log((A == B == 1)); 

returns true.

How does this "ternary" kind of comparison work?

解决方案

First, we need to understand that a == comparison between a number and a boolean value will result in internal type conversion of Boolean value to a number (true becomes 1 and false becomes 0)

The expression you have shown is evaluated from left to right. So, first

A == B

is evaluated and the result is true and you are comparing true with 0. Since true becomes 1 during comparison, 1 == 0 evaluates to false. But when you say

console.log((A == B == 1));

A == B is true, which when compared with number, becomes 1 and you are comparing that with 1 again. That is why it prints true.

这篇关于(A == B == C)比较在JavaScript中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆