JS数据值的严格比较与抽象比较

299 阅读1分钟

#等值比较操作


WHAT

「严格值比较」:===

「抽象值比较」或自动转换比较:==

`比较操作的规则

==先转换类型再比较,===先判断类型,如果不是同一类型直接为false。

「严比」是类型和值都进行比较,「抽象比较」则比较的是抽象语义,例如空串与0的语义相似,可看成相等

`抽象值比较在比较操作前会自动转换类型,转换方式(何种类型被转换)取决某种规则,例如"10" + 10,字符转为数值

JavaScript has both strict and type–converting comparisons. A strict comparison (e.g., ===) is only true if the operands are of the same type and the contents match. The more commonly-used abstract comparison (e.g. ==) converts the operands to the same type before making the comparison.

#大小值比较,先转为基础类型值(primitives),再转像类型,再比较

For relational abstract comparisons (e.g., <=), the operands are first converted to primitives, then to the same type, before comparison.

WHY HOW

我的建议是:如果你的的确确知道你在做什么(了解类型转换的结果),可以用==;否则还是用===吧。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

https://stackoverflow.com/questions/5447024/javascript-comparison-operators-identity-vs-equality

JavaScript中三个等号和两个等号你了解多少

https://www.jb51.net/article/117815.htm

ES6 Object.is()

大部分情况下,你还是可继续三等号,除非非常特殊的需要,才考虑使用Object.is()

《U ES6》