1. 程式人生 > >如何區分null和undefined

如何區分null和undefined

null和undefined是兩種資料型別, 如果硬要區分的話。

null是一種型別, 賦值變數為null型。

未定義的變數, 即為undefined。

var a = null
a  // null
var b
b  // undefined
typeof(b)  // "undefined"

標準解釋

6.1.1 The Undefined Type
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

6.1.2 The Null Type
The Null type has exactly one value, called null.

undefined使用場景:

  • 判斷變數, 判斷函式傳參異常, 判斷物件欄位和方法是否存在(或者正確使用Object.propretype.call(ob, 'key'))
  • es6中應對eslint規範的export default undefined