2012-02-16 65 views
0

我需要检查是否var [2] ==='debug'但是thevar [2]可能是未定义的,所以如果我运行下面的代码时它未定义JavaScript的将抛出一个错误:Javascript:最好的方法来检查可能未定义的变量的值

if (thevar[2] === 'debug') { 
    console.log('yes'); 
} 

所以目前我在做什么是:

if (typeof thevar[2] !== 'undefined') { 
    if (thevar[2] === 'debug') { 
     console.log('yes'); 
    } 
    } 

这真的是做到这一点的最好方法是什么?

+1

dupe:http://stackoverflow.com/a/416327 – 2012-02-16 07:37:18

+0

你的意思是thevar是未定义的而不是thevar [2]? – Laurent 2012-02-16 07:38:01

+0

@AhmetKakıcı这是一个不好的例子,它看起来像问题变成了同样的问题,但接受的答案不适合这个问题。事实上,在这个问题上犯的错误很容易从看到这个问题和例外的答案中产生。 – 2012-02-16 07:46:16

回答

1

你的第一个例子将不会引发错误。对象的未定义属性评估为undefined,但它们不会抛出错误。

var foo = {}; 
var nothing = foo.bar; // foo.bar is undefined, so "nothing" is undefined. 
// no errors. 

foo = []; 
nothing = foo[42]; // undefined again 
// still no errors 

所以,你的第二个例子是不需要的。第一个就足够了。

0

如果你可以运行if (typeof thevar[2] !== 'undefined') ...那么你可以参考thevar,你可以运行其他任何东西。

如果您的数组存在,那么即使该值未定义,对值的检查也可以正常工作。

> var x = []; 
    undefined 
> if (x[0] === "debug") console.log("yes"); 
    undefined 
> if (x[100] === "debug") console.log("yes"); 
    undefined 

仅当数组不存在时才会出现问题。所以只要你知道thevar有价值,那么不需要检查。否则,只是检查是否有thevar值或做一个小的VAR分配伎俩像

var thevar = thevar || []; 
//work with thevar with impunity