I have come accross this strange use if javascript array Can anyone explain me this.
[1,2,3][1,2]
What type of operation is this ?
I have come accross this strange use if javascript array Can anyone explain me this.
[1,2,3][1,2]
What type of operation is this ?
In the expression
var result = [1, 2, 3][1, 2]
The first part [1, 2, 3]
is an array literal, the second part [1, 2]
is an index into the array. So it's equivalent to:
var array = [1, 2, 3];
var index = (1, 2);
var result = array[index];
(1, 2)
is a comma expression. It evaluates its arguments from left to right, and returns the value of the last one, so it's equivalent to just 2
. So the whole thing is equivalent to:
var result = array[2];
which sets result
to 3
.