JQuery/Javascript:检查 var 是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13944100/
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-24 15:11:52  来源:igfitidea点击:

JQuery/Javascript: check if var exists

javascriptjqueryvariables

提问by MeltingDog

Possible Duplicate:
How can I check whether a variable is defined in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

可能的重复:
如何检查 JavaScript 中是否定义了变量?
是否有标准函数来检查 JavaScript 中的 null、未定义或空白变量?

I have a script that occurs in two parts.

我有一个分两部分出现的脚本。

The first part sets up a var:

第一部分设置一个var:

var pagetype = "textpage";

The 2nd part is a simple if statement:

第二部分是一个简单的 if 语句:

if(pagetype == "textpage") {
//do something
};

Now the 2nd part, the if statement, appears on all pages of my site. But the first part, where the var is declared, only appears on some of my pages.

现在第二部分,if 语句,出现在我网站的所有页面上。但是声明 var 的第一部分只出现在我的一些页面上。

On the pages without the var I naturally get this error:

在没有 var 的页面上,我自然会收到此错误:

Uncaught ReferenceError: pagetype is not defined

So my question is: is there a way with JavaScript or JQ to detect if a var exists at all (not just if it has data assigned to it)?

所以我的问题是:有没有办法用 JavaScript 或 JQ 来检测一个 var 是否存在(不仅仅是它是否有分配给它的数据)?

I am imagining I would just use another if statment, eg:

我想我只会使用另一个 if 语句,例如:

if ("a var called pagetypes exists")....

回答by elclanrs

I suspect there are many answers like this on SO but here you go:

我怀疑在 SO 上有很多这样的答案,但你去吧:

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
  ...
}

回答by Blender

You can use typeof:

您可以使用typeof

if (typeof pagetype === 'undefined') {
    // pagetype doesn't exist
}

回答by jermel

For your case, and 99.9% of all others elclanrsanswer is correct.

对于您的情况,其他所有elclanrs答案的99.9%都是正确的。

But because undefinedis a valid value, if someone were to test for an uninitialized variable

但是因为undefined是一个有效值,如果有人要测试未初始化的变量

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

确定 var 是否存在唯一 100% 可靠的方法是捕获异常;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

但我永远不会这样写

回答by Bruno

To test for existence there are two methods.

检验是否存在有两种方法。

a. "property" in object

一种。 "property" in object

This method checks the prototype chain for existence of the property.

此方法检查原型链是否存在该属性。

b. object.hasOwnProperty( "property" )

object.hasOwnProperty( "property" )

This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

此方法不会在原型链上检查属性是否存在,它必须存在于您正在调用该方法的对象中。

var x; // variable declared in global scope and now exists

"x" in window; // true
window.hasOwnProperty( "x" ); //true

If we were testing using the following expression then it would return false

如果我们使用以下表达式进行测试,那么它将返回 false

typeof x !== 'undefined'; // false

回答by Jason

Before each of your conditional statements, you could do something like this:

在每个条件语句之前,您可以执行以下操作:

var pagetype = pagetype || false;
if (pagetype === 'something') {
    //do stuff
}

回答by RobG

It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:

除了使用 try..catch 导致未声明的错误外,无法确定变量是否已声明。测试如下:

if (typeof varName == 'undefined') 

do not tell you if varNameis a variable in scope, only that testing with typeof returned undefined. e.g.

不要告诉你 ifvarName是范围内的变量,只有 typeof 的测试返回未定义。例如

var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true

In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in:

在上面,您无法判断 foo 已声明但 bar 未声明。您可以使用in以下方法测试全局变量:

var global = this;
...
'bar' in global;  // false

But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.

但是全局对象是唯一可以访问的变量对象*,不能访问任何其他执行上下文的变量对象。

The solution is to always declare variables in an appropriate context.

解决方案是始终在适当的上下文中声明变量。

  • The global object isn't really a variable object, it just has properties that match global variables and provide access to them so it just appears to be one.
  • 全局对象并不是真正的变量对象,它只是具有匹配全局变量并提供对它们的访问的属性,因此它看起来只是一个。