2012-02-16 34 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 
相關問題