简体   繁体   English

如何检查 JavaScript 中是否存在变量?

[英]How can I check if a variable exist in JavaScript?

I am not asking if the variable is undefined or if it is null .我不是在问变量是未定义还是null I want to check if the variable exists or not.我想检查变量是否存在。 Is this possible?这可能吗?

The typeof techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined. typeof技术不起作用,因为它们不区分什么时候根本没有声明变量,什么时候声明了变量但没有赋值,或者声明并设置为 undefined。

But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error.但是,如果您尝试使用尚未在 if 条件(或赋值右侧)中声明的变量,则会出现错误。 So this should work:所以这应该工作:

var exists = true;
try {
    if (someVar)
        exists = true;
} catch(e) { exists = false; }
if (exists)
   // do something - exists only == true if someVar has been declared somewhere.

I use this function:我使用这个 function:

function exists(varname){
    try {
        var x = eval(varname);
        return true;
    } catch(e) { return false; }
}

Hope this helps.希望这可以帮助。

if ('bob' in window) console.log(bob);

Keep in mind with this way, even if you declared a variable with var , that would mean it exists.请记住,即使您使用var声明了一个变量,也意味着它存在。

What you're after is:你追求的是:

window.hasOwnProperty("varname");

A safer approach might even be:更安全的方法甚至可能是:

this.hasOwnProperty("varname");

Depends on your calling context though...取决于您的调用上下文...

When you try to access a variable which is not declared in the context, you will see that the error message says it is undefined.当您尝试访问未在上下文中声明的变量时,您将看到错误消息说它未定义。 This is the real check you may perform to see if the variable if defined or not than null check.这是您可以执行的真正检查,以查看变量是否已定义,而不是 null 检查。

If you don't need to know at runtime use JSLint.如果您不需要在运行时知道,请使用 JSLint。 Also remember that javascript var statements are hoisted, so even if the var is inside an if block it will still be defined.还要记住 javascript var 语句被提升,所以即使 var 在 if 块中,它仍然会被定义。

Honestly I think if you are not sure if a variable is defined you are doing something wrong and should refactor your code.老实说,我认为如果您不确定是否定义了变量,那么您做错了什么,应该重构您的代码。

try this尝试这个

var ex=false;
try {(ex=myvar)||(ex=true)}catch(e) {}
alert(ex);

where ex is true if myvar has been declared.如果已声明myvar ,则ex为真。

working example: http://jsfiddle.net/wcqLz/工作示例: http://jsfiddle.net/wcqLz/

I think it depends on what you want to do with the variable.我认为这取决于你想对变量做什么。

Let's say, for example, you have a JS library that will call a function if it has been defined and if not, then not.例如,假设您有一个 JS 库,如果它已定义,它将调用 function,如果没有,则不。 You probably know already that functions are first level objects in JS and are as such variables.您可能已经知道函数是 JS 中的第一级对象,并且是变量。

You could be tempted to ask first if it exists, and then call it.您可能会想先询问它是否存在,然后再调用它。 But you can just as well wrap the attempt at calling it in a try/catch block.但是您也可以将调用它的尝试包装在 try/catch 块中。

Example of code that calls a function, if defined, before and after firing an event:在触发事件之前和之后调用 function(如果已定义)的代码示例:

function fireEvent(event)
{
    try
    {
        willFireEvent(event); // Is maybe NOT defined!
    } catch(e) {}

    //... perform handler lookup and event handling

    try
    {
        hasFiredEvent(event); // Might also NOT exist!
    } catch(e) {}
}

So instead of checking for the variable, catch the error instead:因此,与其检查变量,不如捕获错误:

var x;

try
{
    x = mayBeUndefinedVar;
}
catch (e)
{
    x = 0;
}

Whether this is a good thing or not in terms of performance, etc., depends on what you're doing...这在性能等方面是否是一件好事,取决于你在做什么......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM