JavaScript检查是否未定义–如何在JS中测试未定义

427 阅读2分钟

在 JavaScript 中,未定义的变量或任何没有值的变量总是会返回“未定义”。这与 null 不同,尽管两者都意味着一个空状态。

通常会在声明变量后为其赋值,但情况并非总是如此。

当一个变量被声明或初始化但没有赋值给它时,JavaScript 会自动显示“未定义”。它看起来像这样:

let myStr;

console.log(myStr); // undefined

此外,当尝试访问不存在的数组或对象中的值时,它会抛出undefined.

let user = {
    name: "John Doe",
    age: 14
};

console.log(user.hobby); // undefined

这是另一个例子:

let myArr = [12, 33, 44];

console.log(myArr[7]); // undefined

在本文中,将了解可用于了解变量是否undefined在 JavaScript 中的各种方法和方法。如果想在使用未定义的变量执行操作时避免代码抛出错误,这是必要的。

这里有三种标准方法可以帮助检查变量undefined是否在 JavaScript 中:

if(myStr === undefined){}
if(typeof myArr[7] === "undefined"){}
if(user.hobby === void 0){}

现在让我们更详细地解释这些方法中的每一个。

如何通过直接比较检查 JavaScript 中的变量是否未定义

首先想到的方法之一是直接比较

let user = {
    name: "John Doe",
    age: 14
};

if (user.hobby === undefined) {
    console.log("This is undefined");
}

这也适用于数组,如下所示:

let scores = [12, 34, 66, 78];

if (scores[10] === undefined) {
    console.log("This is undefined");
}

它肯定也适用于其他变量:

let name;

if (name === undefined) {
    console.log("This is undefined");
}

如何在 JavaScript 中检查变量是否未定义typeof

我们还可以使用变量的类型来检查它是否为undefined. 幸运的是,未定义是未定义值的数据类型,如下所示:

let name;

console.log(typeof name); // "undefined"

有了这个,我们现在可以使用数据类型来检查我们上面看到的所有类型的数据的未定义。以下是我们考虑的所有三种情况的检查结果:

if(typeof user.hobby === "undefined"){}
if(typeof scores[10] === "undefined"){}
if(typeof name === "undefined"){}

如何使用Void运算符检查 JavaScript 中的变量是否未定义

void运算符通常用于获取原始undefined值。您可以使用void(0)类似于“ void 0”的“”来执行此操作,如下所示:

console.log(void 0); // undefined
console.log(void(0)); // undefined

实际上,这就像直接比较(我们之前看到的)。void(0)但是我们会用or替换 undefined ,void 0如下所示:

if(typeof user.hobby === void 0){}
if(typeof scores[10] === void 0){}
if(typeof name === void 0){}

或者像这样:

if(typeof user.hobby === void(0)){}
if(typeof scores[10] === void(0)){}
if(typeof name === void(0)){}