JavaScript中null與undefined區別

來源:互聯網
上載者:User

null 與 undefined 是 JavaScript 的兩個類型,類型的值如下:

類型
null 只有一個值 null
undefined 只有一個值 undefined

null 表示變數取值為 null – 換句話說,取值即不是字串也不是數字也不是真假值也不是對象。
undefined 表示變數已經聲明,但未賦值,或賦值 undefined。

比如:

var a; // 變數已聲明,未賦值
var b = undefined; // 變數已聲明,則賦值 undefined
a === b;
a === b 的輸出結果是 true。

所以我們可以簡單地區別它們:
undefined 表示沒找到變數的值 – 找不到值
null 表示找到變數的值是 null – 找得到值

再看判斷 null 與 undefined

這裡所說的判斷,是指判斷變數的值是否就是 null 或 undefined


null 與 undefined 是它們所屬類型的唯一一個值。所以判斷方法非常方便,只要我們使用恒等比較(===)。
a 即 undefined

var a;
a === undefined;

上面的代碼將輸出 true,即 a 為 undefined。

a 為 null
var a = null;
a === null;
上面的代碼將輸出 true,即 a 是 null。

當然,恒等比較有一個前提,就是變數已經存在,如果變數尚未聲明,引用未聲明的變數會拋出錯誤。
i === undefined;

以上代碼執行後會拋出錯誤:

ReferenceError: i is not defined

所以使用 typeof 來檢查變數是否為 undefined 會更安全:
typeof i === 'undefined'; // 如果 i 未聲明,或 i 已聲明但未賦值,結果為 true
但 typeof 檢查變數值是否為 null 時,輸出結果是 “object”,這個結論並不準確。以下方法才是對的且安全的:

var a = null;
Object.prototype.toString.call(a).slice(8, -1);

它會輸出 Null,表示變數 a 的值是 null。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.