javascript - 为什么1==1==1返回true, "1"= ="1"= ="1"返回true, "a"= ="a"= ="a"返回false?

标签 javascript

<分区>

function a() { return (1 == 1 == 1); }
function b() { return ("1" == "1" == "1"); }
function c() { return ("a" == "a" == "a"); }

我在 Chrome 的控制台中测试了上面的代码,出于某种原因,a() 返回 true,b() 返回 true,而 c() 返回 false。

为什么会这样?

最佳答案

因为您正在比较第一个相等的( bool )结果与(非 bool )第三个值。

在代码中,1 == 1 == 1等价于(1 == 1) == 1等价于true == 1.

这意味着这三个方法可以更简单地写成:

function a() { return (true == 1); }
function b() { return (true == "1"); }
function c() { return (true == "a"); }

这些比较根据 these rules 进行(强调我的):

If the two operands are not of the same type, JavaScript converts the operands, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

那么 c 中发生的事情是 "a" 被转换为数字(给出 NaN ),结果是 strictly comparedtrue 转换为数字(给出 1)。

因为 1 === NaNfalse,所以第三个函数返回 false。很容易看出为什么前两个函数将返回 true

关于javascript - 为什么1==1==1返回true, "1"= ="1"= ="1"返回true, "a"= ="a"= ="a"返回false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561542/

相关文章:

javascript - 在 Bootstrap 弹出窗口内执行 JS

javascript - AngularJs 中的自定义排序

javascript - HTML + JavaScript + CSS 精简工具

Javascript 无限循环遍历数组不起作用

javascript - 如何将unicode字符放入javascript

javascript - VueJs : How to pass a 'computed function' value from child component to the parent component using $emit(optionalPayload) and $on?

javascript - Java:Javascript 函数不会在 Wicket 按钮的 onclick 事件上触发

javascript - 动态更改 youtube 上的视频 ID

javascript - 非常奇怪的 Javascript 范围问题

javascript - 使用另一个方法中的变量