javascript - 需要对等号运算符 (==) 进行一些说明

标签 javascript

<分区>

我对下面关于相等比较运算符的陈述感到困惑 ==

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 other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

但是 alert(true == "true")alert(false == "false") 都返回 false。为什么会这样?

If either operand is a number or a boolean, the operands are converted to numbers if possible

JavaScript 在什么情况下将 true 和 "true"转换为数字?前面的示例没有将它们转换为数字。

看了这些例子,我的疑惑就更多了:

''        ==   '0'           // false
0         ==   ''            // true
0         ==   '0'           // true
false     ==   'false'       // false
false     ==   '0'           // true
  • ''false'0'true,但为什么输出为假的?
  • 0 将被解释为 false'' 也是 false。然后它变为 true。我能理解这一点。
  • 为什么当 0false 时,'0' 被解释为 true
  • 为什么 false 被解释为 false'0' 被解释为 true

有人可以更详细地解释 == 运算符的工作原理吗?

最佳答案

=== // strict check. Will compare value and type

== // will check only value not type

所以,

0         ==    ''            // true

0         ===   ''            // false

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?

关于javascript - 需要对等号运算符 (==) 进行一些说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109144/

相关文章:

javascript - Twitter Bootstrap Typeahead 功能类似于 Google Chrome Omnibox

javascript - 如何通过某个键对数组中的对象值求和?

javascript - 防止 select2 的标签文本中出现空格

javascript - 有关 JavaScript 和复杂对象描述的 Visual Studio Intellisense 文档

javascript - 如何对调用同一文件/类中其他函数的函数进行单元测试,以便我无法模拟它们?

javascript - 添加 onfocus 监听器而不是 onload

javascript - 跳过 MP3 会导致播放器在 Webkit 浏览器中中断

javascript - 从对象创建新集合的函数式方法是什么?

javascript - 使用 JavaScript 链接抓取网页

javascript - 防止浏览器重新定位通过制表符导航到的焦点元素