Title: Why you should use Object.is() in equality comparison
Author: TarekAlQaddy
Website: https://www.jstips.co/en/javascript/why-you-should-use-Object.is()-in-equality-comparison/
We all know that JavaScript is loosely typed and in some cases it fall behind specially when it comes to equality comparison with ‘==’, comparing with ‘==’ gives unexpected results due to whats called coercion or casting “converting one of the 2 operands to the other’s type then compare”.
我們都知道JavaScript是弱型別語言,在某些情況下,當與“ ==”進行相等性比較時,它特別落后,使用“ ==”進行比較可能會“將2個運算元中的一個強制轉換為另一種型別然后進行比較”而產生意外結果,
1 0 == ' ' //true 2 null == undefined //true 3 [1] == true //true
So they provided us with the triple equal operator ‘===’ which is more strict and does not coerce operands, However comparing with ‘===’ is not the best solution you can get:
因此Javascript提供了三等運算子,三等運算子更加嚴格并且不會將運算元進行強制型別轉換,然而三等運算子也不是最好的解決方案,也存在問題:
1 NaN === NaN //false
The great news that in ES6 there is the new ‘Object.is()’ which is better and more precise it has the same features as ‘===’ and moreover it behaves well in some special cases:
好訊息是,在ES6中有一個新的“ Object.is()”,它更好,更精確,它具有與“ ===”相同的功能,而且在某些特殊情況下,其表現還不錯:
1 Object.is(0 , ' '); //false 2 Object.is(null, undefined); //false 3 Object.is([1], true); //false 4 Object.is(NaN, NaN); //true
Mozilla team doesn’t think that Object.is is “stricter” than ‘===’ they say that we should think of how this method deal with NaN, -0 and +0 but overall I think it is now a good practice in real applications.
Mozilla團隊不認為"Object.is()"比“ ===”更“嚴格”,應該考慮該方法如何處理NaN,-0和+0,但總的來說,我認為這是一種最佳實踐,
Now this table illustrates..
下表所示:

參考:
Object.is() - JavaScript | MDN
Equality comparisons and sameness
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/154336.html
標籤:JavaScript
上一篇:三流大專轉行成功的前端之路
下一篇:ios輸入法彈出輸入框定位錯亂
