为什么 [5,6,8,7][1,2] = 8 在 JavaScript 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7421013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does [5,6,8,7][1,2] = 8 in JavaScript?
提问by Joe
I can't wrap my mind around this quirk.
我无法理解这个怪癖。
[1,2,3,4,5,6][1,2,3]; // 4
[1,2,3,4,5,6][1,2]; // 3
I know [1,2,3] + [1,2] = "1,2,31,2"
, but I can't find what type or operation is being performed.
我知道[1,2,3] + [1,2] = "1,2,31,2"
,但我找不到正在执行的类型或操作。
回答by Lightness Races in Orbit
[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`.
The second [...]
cannot be an array, so it's an array subscript operation. And the contents of a subscript operation are not a delimited list of operands, but a single expression.
第二个[...]
不能是数组,所以是数组下标操作。并且下标操作的内容不是分隔的操作数列表,而是单个表达式。
Read more about the comma operator here.
在此处阅读有关逗号运算符的更多信息。
回答by Mike Samuel
Because (1,2) == 2
. You've stumbled across the comma operator(or simpler explanation here).
因为(1,2) == 2
。您偶然发现了逗号运算符(或此处更简单的解释)。
Unless commas appear in a declaration list, parameter list, object or array literal, they act like any other binary operator. x, y
evaluates x
, then evaluates y
and yields that as the result.
除非逗号出现在声明列表、参数列表、对象或数组文字中,否则它们的作用就像任何其他二元运算符。 x, y
评估x
,然后评估y
并产生结果。
回答by Imdad
[1,2,3,4,5,6][1,2,3];
Here the second box i.e. [1,2,3]
becomes [3]
i.e. the last item so the result will be 4
for example if you keep [1,2,3,4,5,6]
in an array
这里的第二个框 ie[1,2,3]
成为[3]
ie 最后一个项目,因此结果将是 4 例如,如果您保留[1,2,3,4,5,6]
在数组中
var arr=[1,2,3,4,5,6];
arr[3]; // as [1,2,3] in the place of index is equal to [3]
similarly
相似地
*var arr2=[1,2,3,4,5,6];
// arr[1,2] or arr[2] will give 3*
But when you place a + operator in between then the second square bracket is not for mentioning index. It is rather another array That's why you get
但是当你在中间放置一个 + 运算符时,第二个方括号不是用于提及索引。它是另一个数组这就是为什么你得到
[1,2,3] + [1,2] = 1,2,31,2
i.e.
IE
var arr_1=[1,2,3];
var arr_2=[1,2];
arr_1 + arr_2; // i.e. 1,2,31,2
Basically in the first case it is used as index of array and in the second case it is itself an array.
基本上在第一种情况下它用作数组的索引,在第二种情况下它本身就是一个数组。