Js中==與===


Js中==與===

JavaScript中提供==相等運算符與===嚴格相等運算符,建議是只要變量的數據類型能夠確定,一律使用===,各種類型的值的比較可以參考Js真值表

==相等運算符

==在判斷相等時會進行隱式的類型轉換, 其比較遵循一些原則,即先轉換類型再比較。

  • 如果有一個操作數是布爾值,則在比較相等性之前先將其轉換為數值,即是調用Number()方法。
  • 如果一個操作數是字符串,另一個是數值,在比較相等性之前先將字符串轉換為數值,同樣調用Number()方法。
  • 如果一個操作數是對象,另一個操作數不是,則調用對象的valueOf()toString()方法把對象轉換成基礎類型的值再比較,除Date對象外,會優先嘗試使用valueOf()方法,用得到的基本類型按照前面的規則進行比較。
  • 以及null == undefined,此外任何其他組合,都不相等。
1 == true //true // Number Boolean
2 == true //false
1 == "1"  //true // Number String
[] == ""  //true // Object String
[] == false // true // Object Boolean
[] == 0   //true // Object Number
[] == {}  //false
[] == []  //false
{} == {}  //false
null == undefined //true

在使用的時候可能會出現一些問題。

0 == "0"  //true
0 == []   //true
"0" == [] // false

如果是直接實現了valueOf()toString()的方法,而不是調用原型鏈上的Object.prototype.valueOf()Object.prototype.toString()方法,甚至能夠產生異常。

var obj = {valueOf: function(){ return {} }, toString: function(){ return {}}}
console.log(obj == 0) // Uncaught TypeError: Cannot convert object to primitive value

===嚴格相等運算符

===先判斷類型再比較,類型不同直接不相等。
ES6數據類型有NumberStringBooleanObjectSymbolnullundefined

1 === true //false
1 === "1"  //false
[] === ""  //false
null === undefined //false

if

if()也可以看作是一個單獨的運算符類別。

if(true) console.log("exec"); //exec
if(false) console.log("exec");
if(1) console.log("exec"); //exec
if(0) console.log("exec"); 
if(-1) console.log("exec"); //exec
if("true") console.log("exec"); //exec
if("1") console.log("exec"); //exec
if("0") console.log("exec"); //exec
if("") console.log("exec");
if(null) console.log("exec");
if(undefined) console.log("exec");
if("null") console.log("exec"); //exec
if("undefined") console.log("exec"); //exec
if([]) console.log("exec"); //exec
if({}) console.log("exec"); //exec
if([0]) console.log("exec"); //exec
if(NaN) console.log("exec");

每日一題

https://github.com/WindrunnerMax/EveryDay

參考

https://www.zhihu.com/question/31442029
https://thomas-yang.me/projects/oh-my-dear-js/
https://dorey.github.io/JavaScript-Equality-Table/#three-equals


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM