JavaScript 检查变量是否存在(已定义/初始化)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5113374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:42:42  来源:igfitidea点击:

JavaScript check if variable exists (is defined/initialized)

javascriptvariablesinitializationundefined

提问by Samuel Liew

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何东西(字符串、整数、对象、函数等))

if (elem) { // or !elem

or

或者

if (typeof(elem) !== 'undefined') {

or

或者

if (elem != null) {

采纳答案by Samuel Liew

The typeofoperator will check if the variable is really undefined.

typeof运营商将检查变量真的不确定。

if (typeof variable === 'undefined') {
    // variable is undefined
}

The typeofoperator, unlike the other operators, doesn't throw a ReferenceErrorexception when used with an undeclared variable.

typeof运营商,不同于其他运营商,不会抛出的ReferenceError与未声明的变量使用时例外。

However, do note that typeof nullwill return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

但是,请注意,typeof null将返回"object". 我们必须小心避免将变量初始化为 的错误null。为了安全起见,这是我们可以使用的:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}


For more info on using strict comparison ===instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

有关使用严格比较===而不是简单相等的更多信息==,请参阅:
JavaScript 比较中应使用哪个相等运算符 (== vs ===)?

回答by Jim Puls

You want the typeofoperator. Specifically:

你想要typeof操作。具体来说:

if (typeof variable !== 'undefined') {
    // the variable is defined
}

回答by Alireza

In many cases, using:

在许多情况下,使用:

if (elem) { // or !elem

will do the job for you!... this will check these below cases:

将为您完成工作!...这将检查以下情况:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example, if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false
  1. undefined:如果该值未定义并且它是undefined
  2. null:如果它是 null,例如,如果 DOM 元素不存在...
  3. 空字符串''
  4. 0: 数字零
  5. NaN: 不是数字
  6. 错误的

So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' 'one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:

所以它将涵盖所有情况,但总有一些奇怪的情况我们也想涵盖,例如,一个带有空格的字符串,就像这个' ',这将在 javascript 中定义,因为它在字符串中有空格...例如,在这种情况下,您使用 trim() 再添加一项检查,例如:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

Also, these checks are for valuesonly, as objects and arrays work differently in Javascript, empty array []and empty object {}are always true.

此外,这些检查仅针对,因为对象和数组在 Javascript 中的工作方式不同,空数组[]和空对象{}始终为true

I create the image below to show a quick brief of the answer:

我创建了下面的图像以显示答案的简要说明:

undefined, null, etc

未定义、空等

回答by Brian Kelley

In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:

在 JavaScript 中,可以定义一个变量,但保存 value undefined,因此最常见的答案在技术上是不正确的,而是执行以下操作:

if (typeof v === "undefined") {
   // no variable "v" is defined in the current scope
   // *or* some variable v exists and has been assigned the value undefined
} else {
   // some variable (global or local) "v" is defined in the current scope
   // *and* it contains a value other than undefined
}

That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):

这可能足以满足您的目的。以下测试具有更简单的语义,可以更轻松地准确描述您的代码行为并自己理解(如果您关心此类事情):

if ("v" in window) {
   // global variable v is defined
} else {
   // global variable v is not defined
}

This, of course, assumes you are running in a browser (where windowis a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in windowis stylistically consistent with using window.nameto refer to globals. Accessing globals as properties of windowrather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.

当然,这假设您在浏览器中运行(其中window是全局对象的名称)。但是,如果您像这样处理全局变量,则可能是在浏览器中。主观上, using'name' in window在风格上与 usingwindow.name指代全局变量一致。将全局变量作为属性window而不是变量访问允许您最大限度地减少在代码中引用的未声明变量的数量(为了 linting),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局变量让你的皮肤爬行,你可能会觉得只用这个相对较长的棒触摸它们会更舒服。

回答by David Tang

In the majority of cases you would use:

在大多数情况下,您会使用:

elem != null

Unlike a simple if (elem), it allows 0, false, NaNand '', but rejects nullor undefined, making it a good, general test for the presence of an argument, or property of an object.

与简单的 不同if (elem),它允许0falseNaN'',但拒绝nullundefined,使其成为一个很好的通用测试,用于测试是否存在参数或对象的属性。



The other checks are not incorrect either, they just have different uses:

其他检查也没有错误,它们只是有不同的用途:

  • if (elem): can be used if elemis guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefinedor null).

  • typeof elem == 'undefined'can be used in cases where a specified nullhas a distinct meaning to an uninitialised variable or property.

    • This is the only check that won't throw an errorif elemis not declared(i.e. no varstatement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.
  • if (elem):如果可以被用于elem保证是一个对象,或者如果false0等被认为是“默认”值(因此等同于undefinednull)。

  • typeof elem == 'undefined'可用于指定null对未初始化的变量或属性具有不同含义的情况。

    • 如果未声明(即没有语句,不是 的属性,或不是函数参数),这是唯一不会抛出错误的检查。在我看来,这是相当危险的,因为它允许错别字被忽视。为避免这种情况,请参阅以下方法。elemvarwindow


Also useful is a strict comparison against undefined:

同样有用的是与 的严格比较undefined

if (elem === undefined) ...

However, because the global undefinedcan be overridden with another value, it is best to declare the variable undefinedin the current scope before using it:

但是,因为全局undefined可以被另一个值覆盖,所以最好undefined在使用它之前在当前作用域中声明该变量:

var undefined; // really undefined
if (elem === undefined) ...

Or:

或者:

(function (undefined) {
    if (elem === undefined) ...
})();

A secondary advantage of this method is that JS minifiers can reduce the undefinedvariable to a single character, saving you a few bytes every time.

这种方法的第二个优点是 JS 压缩器可以将undefined变量减少到单个字符,每次为您节省几个字节。

回答by Fred Gandt

Check if window.hasOwnProperty("varname")

检查是否windowhasOwnProperty( " varname")

An alternative to the plethora of typeofanswers;

众多typeof答案的替代方案;

Globalvariables declared with a var varname = value;statement in the global scope

var varname = value;全局范围内的语句声明的全局变量

can be accessed as properties of the window object.

可以作为 window 对象的属性访问。

As such, the hasOwnProperty()method, which

因此,该hasOwnProperty()方法

returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)

can be used to determine whether

返回一个布尔值,指示对象是否将指定的属性作为自己的属性(而不是继承它)

可以用来判断是否

a varof "varname"has been declared globally i.e.is a property of the window.

var“varname的”已在全球宣布是的一个属性window

// Globally established, therefore, properties of window
var foo = "whatever", // string
    bar = false,      // bool
    baz;              // undefined
//  window.qux does not exist

console.log( [
    window.hasOwnProperty( "foo" ), // true
    window.hasOwnProperty( "bar" ), // true
    window.hasOwnProperty( "baz" ), // true
    window.hasOwnProperty( "qux" )  // false
] );

What's great about hasOwnProperty()is that in calling it, we don't use a variable that might as yet be undeclared - which of course is half the problem in the first place.

很棒的hasOwnProperty()是,在调用它时,我们没有使用可能尚未声明的变量——这当然是问题的一半。

Although not alwaysthe perfector idealsolution, in certain circumstances, it's just the job!

虽然不是经常完美理想的解决方案,在某些情况下,它只是工作!

Notes

笔记

The above is true when using varto define a variable, as opposed to letwhich:

var用于定义变量时上述情况是正确的,而不是let

declares a block scope local variable, optionally initializing it to a value.

is unlike the varkeyword, which defines a variable globally, or locally to an entire function regardless of block scope.

At the top level of programs and functions, let, unlike var, does not create a property on the global object.

声明一个块作用域局部变量,可选择将其初始化为一个值。

var关键字不同,它定义了一个全局变量,或者是整个函数的局部变量,而不管块的作用域如何。

在程序和函数的顶层let,与 不同var, 不会在全局对象上创建属性。

For completeness:constconstants are, by definition, not actually variable (although their content can be); more relevantly:

为了完整性:const根据定义,常量实际上并不是变量(尽管它们的内容可以是);更相关的是:

Global constants do not become properties of the window object, unlike varvariables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.

The value of a constant cannot change through reassignment, and it can't be redeclared.

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

var变量不同,全局常量不会成为 window 对象的属性。需要一个常量的初始化器;也就是说,您必须在声明它的同一语句中指定它的值。

常量的值不能通过重新分配而改变,也不能重新声明。

const 声明创建一个对值的只读引用。这并不意味着它持有的值是不可变的,只是变量标识符不能重新分配。

Since letvariables or constconstants are never properties of any object which has inherited the hasOwnProperty()method, it cannot be used to check for their existence.

由于let变量或const常量永远不是继承该hasOwnProperty()方法的任何对象的属性,因此不能用于检查它们的存在。

Regarding the availability and use of hasOwnProperty():

关于可用性和使用hasOwnProperty()

Every object descended from Objectinherits the hasOwnProperty()method. [...] unlike the inoperator, this method does not check down the object's prototype chain.

Object继承的每个对象都继承了该hasOwnProperty()方法。[...] 与in运算符不同,此方法不会检查对象的原型链。

回答by John Slegers

How to check if a variable exists

如何检查变量是否存在

This is a pretty bulletproof solution for testing if a variable exists and has been initialized :

这是一个非常可靠的解决方案,用于测试变量是否存在并已初始化:

var setOrNot = typeof variable !== typeof undefined;

It is most commonly used in combination with a ternary operatorto set a default in case a certain variable has not been initialized :

它最常与三元运算符结合使用以设置默认值,以防某个变量尚未初始化:

var dark = typeof darkColor !== typeof undefined ? darkColor : "black";


Problems with encapsulation

封装问题

Unfortunately, you cannot simply encapsulate your check in a function.

不幸的是,您不能简单地将支票封装在一个函数中。

You might think of doing something like this :

你可能会想到做这样的事情:

function isset(variable) {
    return typeof variable !== typeof undefined;
}

However, this will produce a reference error if you're calling eg. isset(foo)and variable foohas not been defined, because you cannot pass along a non-existing variable to a function :

但是,如果您调用例如,这将产生参考错误。isset(foo)并且变量foo尚未定义,因为您不能将不存在的变量传递给函数:

Uncaught ReferenceError: foo is not defined

未捕获的 ReferenceError: foo 未定义



Testing whether function parameters are undefined

测试函数参数是否未定义

While our issetfunction cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :

虽然我们的isset函数不能用于测试变量是否存在(出于上文解释的原因),但它确实允许我们测试函数的参数是否未定义:

var a = '5';

var test = function(x, y) {
    console.log(isset(x));
    console.log(isset(y));
};

test(a);

// OUTPUT :
// ------------
// TRUE
// FALSE

Even though no value for yis passed along to function test, our issetfunction works perfectly in this context, because yis known in function testas an undefinedvalue.

即使对于没有价值y被一起传递给函数test,我们的isset功能完美的作品在这方面,因为y在功能上被称为test作为一个undefined值。

回答by RajeshKdev

There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.

当您执行简单的分配和相关检查时,还有另一种快捷方式来检查这一点。只需使用条件(三元)运算符。

var values = typeof variable !== 'undefined' ? variable : '';

Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.

当您尝试使用引用变量的实例赋值来声明全局变量时,这也会很有帮助。

If you wanted to check variable shouldn't be undefinedor null. Then perform below check.

如果你想检查变量不应该是undefinedor null。然后执行以下检查。

When the variable is declared, and if you want to check the value, this is even Simple:and it would perform undefinedand nullchecks together.

当变量被声明时,如果你想检查它的值,这甚至很简单:它会一起执行undefinednull检查。

var values = variable ? variable : '';

回答by user2878850

Short way to test a variable is not declared (not undefined) is

测试变量未声明(非未定义)的简短方法是

if (typeof variable === "undefined") {
  ...
}

I found it useful for detecting script running outside a browser (not having declared windowvariable).

我发现它对于检测在浏览器外运行的脚本很有用(没有声明window变量)。

回答by Alan Geleynse

It depends if you just care that the variable has been defined or if you want it to have a meaningful value.

这取决于您是只关心已定义变量还是希望它具有有意义的值。

Checking if the type is undefined will check if the variable has been defined yet.

检查类型是否未定义将检查变量是否已定义。

=== nullor !== nullwill only check if the value of the variable is exactly null.

=== null或者!== null只会检查变量的值是否正好是null

== nullor != nullwill check if the value is undefinedor null.

== nullor!= null将检查值是否为undefinednull

if(value)will check if the variable is undefined, null, 0, or an empty string.

if(value)将检查变量是undefinednull0,或一个空字符串。