2016-09-28 43 views
1

我有一個關於JavaScript的結果的問題,因爲我不太瞭解它。 爲什麼,如果我使用此代碼它得到了一個結果:javascript中的[1] [1]和[1] [0]的結果

var a =[1][1]; 
var b = [1][0]; 
if(a){console.log(true);}else{console.log(false);} --> returns false 

if(b){console.log(true);}else{console.log(false);} --> returns true 

誰能幫我解釋的JavaScript如何解釋這個結果的準確方法是什麼? 非常感謝!

最好的問候, 維克多

回答

2

漂亮其實很簡單,讓我們把它分解:

var a =[1][1]; 

斷下來就是:

var a = [1]; //An array with the value '1' at the 0 index 
a = a[1]; //assigns a the result of the 1 index, which is undefined 

同樣的,b - 但b使用0指數,其定義爲(如1);

aundefined這是虛假的,而b是1 - 這是truthy。

+0

非常感謝您!我現在明白了。在時間限制消失後,我會給出答案:) – Victor

2

Basicall您正在使用數組中的值與一個元素1

a得到undefined,因爲沒有索引爲1的元素。
b得到1,因爲索引0處的元件1

var a = [1][1]; // undefined 
 
var b = [1][0]; // 1 
 

 
console.log(a); // undefined 
 
console.log(b); // 1 
 

 
if (a) { 
 
    console.log(true); 
 
} else { 
 
    console.log(false); // false 
 
} 
 

 
if (b) { 
 
    console.log(true); // true 
 
} else { 
 
    console.log(false); 
 
}

+0

謝謝你:)但tymeJV已經解釋了,但我很高興你們所有人都幫了忙! – Victor