1. 程式人生 > >慕課網JavaScript深入淺出學習筆記之數據類型

慕課網JavaScript深入淺出學習筆記之數據類型

bool ins 等於 對象的比較 defined 轉換 arr ply 理解

JavaScript數據類型

六種數據類型(五種原始類型,一種對象類型)

  • number
  • sttring
  • boolean
  • null
  • undefined
  • object #對象
    • Function
    • Array
    • Date
    • ...

javascript數據類型是弱數據類型,在定義變量時無需指定數據類型。

var num = 32;
num = "this is a string";

32 + 32  // 64 #加法運算
//"+"理解為字符串拼接,"-"理解為減法運算
"32" + 32 // "3232" # 字符串拼接
"32" - 32 // 0 # 減法運算

隱式轉換

巧用“+”/"-"規則轉換類型

var num = "string";
num - 0 //將num對象轉換為number

var num = 123;
num + "" //將num對象轉換為string

a === b #嚴格等於

  • 首先判斷類型,類型不同,返回false
  • 類型相同:
  • number //數值一樣
  • string //長度和內容都一樣
  • null === null
  • undefined === undefined
  • NaN != NaN //NaN跟任何東西比較都不相等,包括跟自己比較。
  • new object != new object //就算是兩個空對象,也不相等。
  • [1, 2] != [1, 2] //內容相同,順序一樣,也不相等,因為她們不是完全相同的對象
  • JavaScript中,對象的比較是用引用去比較的

a == b #等於

  • 類型相同,同===
  • 類型不同,嘗試類型轉換再比較:
  • null == undefined //true
  • number == string //嘗試把string轉number,1 == "1.0"為true
  • boolean == ? //boolean轉number,true = 1, false = 0
  • object == number | string //嘗試把對象轉為基本類型 new String(‘hh‘) == ‘hi‘ //true
  • 其他:false

包裝對象

var str = "string"; //string類型
var strObj = new String("string"); //對象類型,string對應的包裝類
str.length //str為基本類型,沒有屬性。當str訪問length屬性時,javascript會把基本類型轉換為對應的包裝對象

類型檢測

typeof

{%note danger%}適合檢測基本類型和function,遇到null失效{%endnote%}

typeof 100    "number"
typeof true     "boolean"
typeof function   "function"
typeof(undefined)  "undefined"
typeof new Object()   "object"
typeof [1, 2]           "object"
typeof NaN           "number"
typeof null         "object" #返回object而不是null,是由於歷史原因

instanceof

instanceof操作符是基於原型鏈去判斷,用法:obj instanceof Object
註意: 不同的window或iframe之間的對象類型檢測不能使用instanceof!

{%note danger%}可以用來檢測自定義對象以及原生對象{%endnote%}

[1, 2] instanceof Array === true
new Object() instanceof Array ===false

Object.prototype.toString.apply()

{%note%}適合內置對象和基本類型,用來檢測null會存在兼容性問題{%endnote%}

Object.prototype.toString.apply([]); === "[object Array]"
Object.prototype.toString.apply(function(){}); === "[object Function]"
Object.prototype.toString.apply(null); === "[object Null]"
Object.prototype.toString.apply(unfefined); === "[object Undefined]"

IE6/7/8 Object.prototype.toString.apply(null); 返回"[object Object]"

慕課網JavaScript深入淺出學習筆記之數據類型