JavaScript中equality(==)的用法解释

不言
不言 转载
2018-11-20 15:40:23 2413浏览

本篇文章给大家带来的内容是关于JavaScript中equality(==)的用法解释,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

神奇之处在哪里

最近负责的项目有涉及到前端的,所以尝试性的写了写js。在处理一个字段非空值的时候,用了 tagert_value == ''来进行判断,然后发生了一件非常奇怪的事情,有用户反馈,自己的target_value = 0的时候,非空值校验不通过。在调试问题的时候,在console状态栏中做了如下尝试:

> 0 == ''
< true

我似乎知道问题出在哪里了。。。没有了解清楚 == 的判断逻辑,所以我打算找来官方的文档瞅瞅。

官方解释

Equality (==, !=)

1、If the types of the two expressions are different, attempt to convert them to string, number, or Boolean.

2、NaN is not equal to anything including itself.

3、Negative zero equals positive zero.

4、null equals both null and undefined.

5、Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.

6、Every other comparison is considered unequal.

查看了官方关于equality的解释,看到第一个就知道为什么结果会是true了。如果表达式两边的类型不一致,比较方法会先尝试将他们转换为string、number、Boolean,然后在进行比较(相等的条件:同样的string、数学上相等的数字、相同的object、相同的布尔值)。
看到这里,基本清楚了,在比较 0 == ’‘的时候先进行了类型装换,那我们来看一下到底是转换的谁啊?

> Number('')
< 0

> var b= ''
> b.toString()
<'0'

非常明显了,int == string 的时候是先将string装换为对应的int值,然后进行比较。

如何避免嘞?

下面强烈介绍 === (strict equality)。严格等于,看着是不是非常厉害呀。人家的官方叫法是Identity (===. !==)。Identity 有点类型悬疑破案的感觉了。
看一下官方的介绍:

Identity (===. !==)
These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal.

在日常开发中,如果没法保证比较表达式两遍的变量的类型一致,建议使用 Identify(===)来比较是否相等。如果变量类型一致,就可以直接使用Equality(==)来比较了。

以上就是JavaScript中equality(==)的用法解释的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除