可以使用 typeof
操作符來判斷一個變量是否為 undefined 類型
let x;
if (typeof x === "undefined") {
console.log("x is undefined");
} else {
console.log("x is defined");
}
也可以使用嚴格相等運算符 ===
來判斷一個變量是否為 undefined
let x;
if (x === undefined) {
console.log("x is undefined");
} else {
console.log("x is defined");
}
注意:不要使用 == 運算符來判斷一個變量是否為 undefined 因為它會在比較之前進行類型轉(zhuǎn)換,可能導(dǎo)致意外的結(jié)果。文章來源:http://www.zghlxwxcb.cn/news/detail-621077.html
如果要判斷一個變量是否未定義(既未聲明也未賦值),可以使用 window.variable 來進行判斷,如果變量未定義,則會拋出一個 ReferenceError 錯誤文章來源地址http://www.zghlxwxcb.cn/news/detail-621077.html
let x;
try {
if (window.x === undefined) {
console.log("x is undefined");
}
} catch (error) {
if (error instanceof ReferenceError) {
console.log("x is not defined");
}
}
到了這里,關(guān)于JavaScript判斷變量是否為undefined的兩種寫法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!