为什么在JavaScript中[5,6,8,7] [1,2] = 8?


278

我不能为这个怪癖全神贯注。

[1,2,3,4,5,6][1,2,3]; // 4
[1,2,3,4,5,6][1,2]; // 3

我知道[1,2,3] + [1,2] = "1,2,31,2",但是我找不到正在执行的类型或操作。

Answers:


387
[1,2,3,4,5,6][1,2,3];
      ^         ^
      |         |
    array       +  array subscript access operation,
                    where index is `1,2,3`,
                    which is an expression that evaluates to `3`.

第二个[...]不能是数组,所以它是数组下标操作。下标操作的内容不是操作数的分隔列表,而是单个表达式。

在此处阅读有关逗号运算符的更多信息。


7
正确..最后使用的索引..更多示例:[1,2,3,4,5,6] [1,2,3] === [1,2,3,4,5,6] [3] ; [1,1,1,5,1,1] [3] === [1,1,1,5,1,1] [1,2,3]; 这样[1,1,1,5,1,1] [3] == 5
mastak 2011年

阅读更多关于逗号运算符的信息, 是一种令人误解的陈述,因为链接的Wiki条目谈到了C和C ++上下文中的逗号运算符,并且这里有JavaScript!
纳瓦兹


21
[1,2,3,4,5,6][1,2,3];

在这里,第二个盒子,即[1,2,3]成为[3]最后一个项目,因此,例如,如果保存[1,2,3,4,5,6]在数组中,结果将是4

var arr=[1,2,3,4,5,6];

arr[3]; // as [1,2,3] in the place of index is equal to [3]

类似地

*var arr2=[1,2,3,4,5,6];

 // arr[1,2] or arr[2] will give 3*

但是,当您在两者之间放置一个+运算符时,第二个方括号就不会提及索引。而是另一个数组,这就是为什么你得到

[1,2,3] + [1,2] = 1,2,31,2

var arr_1=[1,2,3];

var arr_2=[1,2];

arr_1 + arr_2; // i.e.  1,2,31,2

基本上,在第一种情况下,它用作数组的索引,在第二种情况下,它本身就是数组。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.