Understanding Array Subscripting Quirk in JavaScript
In JavaScript, an array subscript operation can sometimes lead to surprising results, leaving many wondering why the result differs from expectations. Consider the following example:
<code class="javascript">[5, 6, 8, 7][1, 2] = 8</code>
Why does this expression return 8?
This behavior stems from how JavaScript handles array subscript operations with non-array second operands. When an array is indexed with a comma-separated list of expressions instead of a single number, the expressions are evaluated sequentially, and the result of the last expression is used as the index.
In this case, the expression [1, 2] is evaluated as follows:
As a result, the array subscript operation becomes:
<code class="javascript">[5, 6, 8, 7][2]</code>
This evaluates to 8, which is the value of the element at index 2 in the array.
Additional Examples
To illustrate further:
<code class="javascript">[1, 2, 3, 4, 5, 6][1, 2, 3]; // 4 [1, 2, 3, 4, 5, 6][1, 2]; // 3</code>
These examples showcase the same behavior. The second operand in the array subscript operation is evaluated as a single expression, resulting in the index value that is used to access the corresponding element in the array.
The above is the detailed content of Why Does `[5, 6, 8, 7][1, 2]` Return 8 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!