DIV CSS 佈局教程網

JavaScript 判斷變數是否有值的方法
編輯:關於JavaScript     

例如:

var a = null;
var b = undefined;

以上這兩種情況都算「沒有值」,因此判斷時必須同時排除兩者:

if (a !== null && a !== undefined) {
    // 有值
}

為什麼不能只判斷一邊

只寫 if (a !== null) 的問題:

var a;
a !== null;   // true —— 但 a 實際上是 undefined,並沒有值

只寫 if (a !== undefined) 的問題:

var a = null;
a !== undefined;   // true —— 但 a 是 null,也沒有值

也就是說,null 與 undefined 是兩件不同的事,單獨排除其中一個都會漏掉另一個。

更簡潔的寫法

由於 null == undefined 為 true(用 == 而非 === 時會做型別轉換),所以只要一行就能同時排除兩者:

if (a != null) {
    // a 既不是 null 也不是 undefined
}

這是 JavaScript 中少數「刻意使用 == 」反而更清晰的場合。若想更明確,也可以寫:

if (a !== null && a !== undefined) { /* ... */ }
// 或
if (typeof a !== "undefined" && a !== null) { /* ... */ }

還要小心「假值」

若需求其實是「變數有實際內容」,那麼除了 null 與 undefined,還得排除空字串、0、NaN 與 false,因為這些在 JavaScript 中都是 falsy:

if (a) { /* 排除 '' 、0 、NaN 、false 、null 、undefined */ }

// 只想排除 null / undefined,但保留 0 與 '',就用 a != null
// 想排除空字串也一起排除,可用
if (a !== null && a !== undefined && a !== "") { /* ... */ }

實務上最常見的錯誤,是對「數字 0」或「空字串」用了 if (a) 判斷,導致合法值被當成沒填寫。判斷前先想清楚:你要排除的是「未定義」,還是「空的內容」?兩者的寫法並不相同。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved