「判斷變數是否為空」是再基本不過的需求,卻也是 JavaScript 最容易寫錯的地方。不同的簡寫方式涵蓋的範圍差很多。
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
var variable2 = variable1;
}
意思很直白:只要 variable1 不是 null、不是 undefined、也不等於空字串,就把它賦給 variable2。
var variable2 = variable1 || '';
|| 取第一個真值運算式,所以 variable1 有值時取它,否則用空字串遞補。
用 == null 同時判斷兩者
var exp = null;
if (exp == null) {
alert("is null");
}
== 會做型別轉換,而 undefined == null 為 true,所以這個寫法能同時攔下兩者。注意:要同時判斷 null 與 undefined 時,這個寫法反而是最簡潔的正确答案。
用 !exp
var exp = null;
if (!exp) {
alert("is null");
}
問題較大:exp 為 undefined、數字 0、空字串 ''、NaN、false 時,都會得到相同結果。這些值彼此並不相同,若 0 是合法輸入就會誤判。
用 typeof exp == "null"
var exp = null;
if (typeof exp == "null") {
alert("is null");
}
永遠不會成立。為了向下相容,typeof null 一律回傳 "object",這是 JavaScript 從第一版留下的 bug,因為修掉會破壞當時已存在的網頁而從未更正。要判斷 null 請用 exp === null。
用 isNull(exp)
var exp = null;
if (isNull(exp)) { ... }
JavaScript 沒有內建的 isNull 函式,除非自己實作,否則會丟 ReferenceError。
直接用 length:
var strings = '';
if (strings.length == 0) {
alert('不能為空');
}
但若使用者輸入的是空格、定位字元或換行呢?length 不為 0,這些資料卻不是我們想要的。此時可以用正規表達式把「空」字元去掉再判斷:
var strings = ' ';
if (strings.replace(/(^\s*)|(\s*$)/g, "").length == 0) {
alert('不能為空');
}
\s 小寫的 s 匹配任何空白字元,包含空格、定位字元、換頁符等,等價於 [ \f\n\r\t\v]。那個正規表達式把頭尾的空白都剃掉。
其實有更清楚的寫法:
if (strings.trim().length === 0) { ... }
// 或
if (!strings.trim()) { ... }
// 同時排除 null 與 undefined,最簡潔
if (value == null) { /* 沒有值 */ }
// 只排除 undefined
if (value === undefined) { }
// 只要不是「有意義的值」就用預設
const name = value ?? '未命名'; // 只對 null / undefined 生效
// 連空字串與 0 也要排除時
const name = value || '未命名'; // 注意 0 會被排除
??(空值合併運算子)是 ES2020 加入的,語意比 || 精準得多:它只在左側為 null 或 undefined 時才取右側,0、''、false 都會被保留。這正是絕大多數「設定預設值」場景真正想要的行為。
可選鏈 ?. 則解決了另一個問題:
const city = user?.address?.city; // 中間任何一層為 null 都不會報錯
比一長串 && 判斷清楚太多。