用于處理 null、NaN 和undefined 的 18 個 JavaScript 代碼片段
Null、NaN 和 undefined 是程序員在使用 JavaScript 時遇到的常見值。
有效處理這些值對于確保代碼的穩(wěn)定性和可靠性至關重要。
因此,在今天這篇文章中,我們將探討 18 個 JavaScript 代碼片段,它們?yōu)樘幚?null、NaN 和未定義場景提供了便捷的解決方案。
這些代碼片段將幫助你通過有效處理這些值來編寫更清晰、更優(yōu)雅的代碼。
1. 檢查是否為null:
要檢查變量是否為 null,可以使用嚴格相等運算符 (===) 將其直接與 null 進行比較:
if (variable === null) {
// Code to handle null value
}
2. 檢查undefined:
同樣,你可以使用 typeof 運算符檢查變量是否為undefined:
if (typeof variable === 'undefined') {
// Code to handle undefined value
}
3. 檢查 NaN:
要檢查值是否為 NaN(非數(shù)字),可以使用 isNaN() 函數(shù):
if (isNaN(value)) {
// Code to handle NaN value
}
4. 如果為 null 或undefined則默認為某個值:
如果變量為 null 或undefined,您可以使用邏輯 OR 運算符 (||) 提供默認值:
const result = variable || defaultValue;
5. 如果為 NaN,則默認為一個值:
如果值為 NaN,您可以使用 isNaN() 函數(shù)以及邏輯 OR 運算符來提供默認值:
const result = isNaN(value) ? defaultValue : value;
6. 將 null 或 undefined 轉(zhuǎn)換為空字符串:
要將 null 或undefined的值轉(zhuǎn)換為空字符串,可以使用邏輯 OR 運算符和空字符串:
const result = variable || '';
7. 將 null 或 undefined 轉(zhuǎn)換為零:
如果需要將 null 或 undefined 轉(zhuǎn)換為零,可以使用邏輯 OR 運算符和數(shù)字零:
const result = variable || 0;
8. 將 null 或 undefined 轉(zhuǎn)換為默認對象:
要將 null 或 undefined 轉(zhuǎn)換為默認對象,可以將邏輯 OR 運算符與空對象文字結合使用:
const result = variable || {};
9. 檢查變量是否為 null 或undefined:
您可以使用邏輯 OR 運算符組合 null 和未定義檢查:
if (variable === null || typeof variable === 'undefined') {
// Code to handle null or undefined value
}
10. 檢查值是否為 null、undefined或 NaN:
將 null、未定義和 NaN 檢查與邏輯 OR 運算符結合起來:
if (variable === null || typeof variable === 'undefined' || isNaN(variable)) {
// Code to handle null, undefined, or NaN value
}
11. unll或undefined的短路評估:
如果變量為 null 或undefined,請使用邏輯 AND 運算符 (&&) 執(zhí)行短路計算:
const result = variable && someFunction();
12. 使用 NaN 進行短路評估:
如果值為 NaN,則可以使用邏輯 AND 運算符進行短路評估:
const result = !isNaN(value) && someFunction();
13. 可選鏈接:
為了避免在訪問可能為 null 或未定義的對象的屬性時出現(xiàn)錯誤,您可以使用可選鏈接運算符 (?.):
const result = object?.property;
14. 空合并運算符:
空值合并運算符 (??) 提供了一種簡潔的方法來為 null 或未定義的變量提供默認值:
const result = variable ?? defaultValue;
15. 將 null 或 undefined 轉(zhuǎn)換為布爾值:
要將 null 或 undefined 轉(zhuǎn)換為布爾值,可以使用邏輯 NOT 運算符 (!):
const result = !!variable;
16. 將 NaN 轉(zhuǎn)換為布爾值:
要將 NaN 轉(zhuǎn)換為布爾值,可以使用 isNaN() 函數(shù)和邏輯 NOT 運算符:
const result = !isNaN(value);
17. 處理函數(shù)參數(shù)中的 null 或 undefined:
您可以使用默認參數(shù)值來處理函數(shù)參數(shù)中的 null 或undefined:
function myFunction(param = defaultValue) {
// Code that uses the parameter
}
18. 從數(shù)組中刪除 null 或undefined的值:
要從數(shù)組中刪除 null 或undefined的值,可以使用 filter() 方法:
const newArray = originalArray.filter((value) => value !== null && typeof value !== 'undefined');
結論:
以上就是我今天與您分享的18 個 JavaScript 代碼片段,希望這些代碼片段對您有用,因為,這些代碼片段可以幫助您有效地處理代碼中的 null、NaN 和undefined的使用場景。
這些代碼片段,無論您需要檢查這些值、提供默認值還是將它們轉(zhuǎn)換為不同的類型,它們都將幫助您編寫更清晰、更優(yōu)雅的 JavaScript 代碼。