JavaScript typeof, null, 和 undefined
JavaScript typeof, null, undefined, valueOf()。
typeof 操作符
你可以使用 typeof 操作符來檢測變數的資料型別。
例項
typeof "John" // 返回 string
typeof 3.14 // 返回 number
typeof false // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
typeof 3.14 // 返回 number
typeof false // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
嘗試一下 ?
![]() |
在JavaScript中,陣列是一種特殊的物件型別。 因此 typeof [1,2,3,4] 返回 object。 |
---|
null
在 JavaScript 中 null 表示 "什麼都沒有"。
null是一個只有一個值的特殊型別。表示一個空物件引用。
![]() |
用 typeof 檢測 null 返回是object。 |
---|
你可以設定為 null 來清空物件:
例項
var
person = null; // 值為 null(空), 但型別為物件
嘗試一下 ?
你可以設定為 undefined 來清空物件:
例項
var
person = undefined; // 值為 undefined,
型別為 undefined
嘗試一下 ?
undefined
在 JavaScript 中, undefined 是一個沒有設定值的變數。
typeof 一個沒有值的變數會返回 undefined。
例項
var person; // 值為 undefined(空), 型別是undefined
嘗試一下 ?
任何變數都可以通過設定值為 undefined 來清空。 型別為 undefined.
例項
person = undefined; // 值為 undefined,
型別是undefined
嘗試一下 ?
undefined 和 null 的區別
例項
null 和 undefined 的值相等,但型別不等:
typeof undefined
// undefined
typeof null // object
null === undefined // false
null == undefined // true
typeof null // object
null === undefined // false
null == undefined // true
嘗試一下 ?