首頁  >  文章  >  web前端  >  JavaScript中equality(==)的用法解釋

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

不言
不言轉載
2018-11-20 15:40:232800瀏覽

這篇文章帶給大家的內容是關於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.com。如有侵權,請聯絡admin@php.cn刪除