JavaScript typeof, null, 和 undefined

2018-09-28 03:49 更新

JavaScript typeof, null, 和 undefined


JavaScript typeof, null, undefined, valueOf()。


typeof 操作符

你可以使用 typeof 操作符來檢測變量的數(shù)據(jù)類型。

實(shí)例

typeof "John"                // 返回 string
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean
typeof [1,2,3,4]             // 返回 object
typeof {name:'John', age:34} // 返回 object

嘗試一下 ?

Note  在JavaScript中,數(shù)組是一種特殊的對(duì)象類型。 因此 typeof [1,2,3,4] 返回 object。 


Null

在 JavaScript 中 null 表示 "什么都沒有"。

null是一個(gè)只有一個(gè)值的特殊類型。表示一個(gè)空對(duì)象引用。

Note 用 typeof 檢測 null 返回是object。

你可以設(shè)置為 null 來清空對(duì)象:

實(shí)例

var person = null;           // Value is null, but type is still an object

嘗試一下 ?

你可以設(shè)置為 undefined 來清空對(duì)象:

實(shí)例

var person = undefined;     // 值為 undefined, type is undefined

嘗試一下 ?


Undefined

在 JavaScript 中, undefined 是一個(gè)沒有設(shè)置值的變量。

typeof 一個(gè)沒有值的變量會(huì)返回 undefined。

實(shí)例

var person;                  // Value is undefined, type is undefined

嘗試一下 ?

任何變量都可以通過設(shè)置值為 undefined 來清空。 類型為 undefined.

實(shí)例

person = undefined;          // 值為 undefined, type is undefined

嘗試一下 ?


Undefined 和 Null 的區(qū)別

typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true

嘗試一下 ?
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)