萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript null 與 undefined 徹底搞懂:區別、類型、判斷最佳實踐

核心定義

特性undefinednull
含義「缺少值」——聲明了但未賦值、不存在的屬性、無返回值的函數「空值」——人為設置的空對象指針,表示「這裡本應有對象但目前為空」
類型undefined (基本類型)object (基本類型,但 typeof null === 'object' 是歷史遺留 Bug)
轉布爾falsefalse
轉數字NaN0
JSON 序列化被忽略 / 變為 null (視庫而定)保留為 null

產生場景對比

產生 undefined 的情況

var a;                    // 變量聲明未賦值
var obj = {}; obj.prop;   // 訪問不存在屬性
function f(){}; f();      // 無返回值函數調用
[1,2][5];                 // 索引越界
void 0;                   // 操作符強制產生 undefined

產生 null 的情況

var a = null;             // 顯式賦值
document.getElementById('not-exist'); // DOM 查找失敗
'string'.match(/regex/);  // 正則無匹配時 (部分情況)
Object.create(null);      // 原型為 null 的對象

經典陷阱:typeof null === 'object'

這是 JavaScript 最初版本的 Bug(第一版用標籤位表示類型,null 全零被誤判為對象),為兼容性永久保留。

正確判斷 null:

function isNull(v) { return v === null; }

相等比較陷阱

null == undefined   // true  (隱式轉換規定)
null === undefined  // false (嚴格相等,類型不同)
null == 0           // false
undefined == 0      // false

建議:永遠使用 === / !==,避免隱式轉換帶來的不可預期行為。

實務判斷模式

1. 判斷變量是否「有值」(非 null/undefined)

if (value != null) { ... } // 利用 == null 同時檢查 null 和 undefined (唯一推薦用 == 的場景)
if (value !== null && value !== undefined) { ... } // 顯式寫法

2. 判斷對象屬性是否存在

'prop' in obj           // 檢查原型鏈含繼承
obj.hasOwnProperty('prop') // 僅自身屬性
obj.prop !== undefined   // 值為 undefined 也會判斷為不存在,慎用

3. 函數參數預設值 (ES6)

function foo(a = 1, b = 2) { ... } // 僅當傳入 undefined 或缺參時生效,null 會保留 null

記憶口訣

  • undefined = 系統說「這裡還沒定義值」
  • null = 程式員說「這裡明確沒有對象」

總結

  • 兩者都是「無值」的表示,但語義不同。
  • typeof undefined === 'undefined',typeof null === 'object' (Bug)。
  • null == undefined 為 true,其餘比較多為 false。
  • 日常判斷用 value == null (雙等) 或顯式 ===,拒絕隱式轉換。
  • ES6 默認參數、解構賦值、可選鏈 ?.、空值合併 ?? 進一步簡化處理。
copyright © 萬盛學電腦網 all rights reserved