如何在JavaScript中检查“未定义”?\[重复\]

JavaScript

达蒙

2020-03-09

测试JavaScript中是否未定义变量的最合适方法是什么?我已经看到了几种可能的方法:

if (window.myVariable)

要么

if (typeof(myVariable) != "undefined")

要么

if (myVariable) //This throws an error if undefined. Should this be in Try/Catch?

第188篇《如何在JavaScript中检查“未定义”?\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
伽罗神奇 2020.03.09

I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source.

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

Of course you could just use typeof though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.

Winter 2020.03.09

就个人而言,我始终使用以下内容:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

在所有现代浏览器(JavaScript 1.8.5或更高版本)中,window.undefined属性都是不可写的。从Mozilla的文档中:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined,我看到了:使用typeof()的一个原因是,如果出现以下情况,它不会引发错误:该变量尚未定义。

我更喜欢有使用的方法

x === undefined 

因为它失败了并且炸毁了我的脸,而不是在以前没有声明x的情况下默默地通过/失败。这提醒我未声明x。我相信应该声明JavaScript中使用的所有变量。

L泡芙Jim 2020.03.09

这篇文章中我读到这样的框架Underscore.js使用此功能:

function isUndefined(obj){
    return obj === void 0;
}
Green蛋蛋 2020.03.09

您可以这样使用typeof

if (typeof something != "undefined") {
    // ...
}
用户7049302300 2020.03.09

如果未定义,则它将不等于包含字符“ undefined”的字符串,因为该字符串不是未定义的。

您可以检查变量的类型:

if (typeof(something) != "undefined") ...

有时,您甚至不必检查类型。如果设置后变量的值不能为假(例如,如果它是一个函数),则可以对变量进行求值。例:

if (something) {
  something(param);
}
神无老丝Davaid 2020.03.09

使用typeof是我的偏爱。在从未声明过变量的情况下它将起作用,这与与=====运算符进行任何比较,使用进行类型强制转换不同ifundefined不同于null,也可能会在ECMAScript 3环境中重新定义,因此比较起来不可靠,尽管现在几乎所有常见环境都符合ECMAScript 5或更高版本)。

if (typeof someUndeclaredVariable == "undefined") {
    // Works
}

if (someUndeclaredVariable === undefined) { 
    // Throws an error
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android