【JavaScript 類型比較】爲何空對象不==true?

【JavaScript 類型比較】爲何空對象不==true?

背景

Boolean()函數爲強制轉換爲布爾類型的函數,其轉換規則以下:
函數

問題

爲何表達式[]==true =>false, 表達式{}==true =>false,按照ToBoolean的規則,這兩個表達式不該該都是真true嗎?spa

示例

在這裏插入圖片描述

解決

預備知識:非嚴格比較操做符==是會作強制類型轉換的,其規則是:
enter image description here
==會根據這些規則,將兩邊強制轉換成相同類型,才進行比較。
其中第七、9條:code

7.If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
9.If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.

大意是:若==兩邊類型不一致,布爾值的會使用Number()強制轉換爲數值型,對象類型會使用ToPrimitive規則進行轉換,ToPrimitive規則以下:
enter image description here
根據這些規則,
對於表達式[]==true:實際上等價於ToPrimitive([]) == ToNumber(true),即Number([].toString()) == Number(true)
在這裏插入圖片描述
對於表達式{}==true:實際上等價於ToPrimitive({}) == ToNumber(true),即Number({}.toString()) == Number(true)
在這裏插入圖片描述
由於NaN爲非數值,由於不可能等於0或1,因此無論是表達式{}==true仍是表達式{}==false,結果都爲false
在這裏插入圖片描述對象

相關文章
相關標籤/搜索