2016-09-28 117 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