Home > Web Front-end > JS Tutorial > body text

Why Does `[5, 6, 8, 7][1, 2]` Return 8 in JavaScript?

DDD
Release: 2024-11-01 10:25:30
Original
307 people have browsed it

Why Does `[5, 6, 8, 7][1, 2]` Return 8 in JavaScript?

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>
Copy after login

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:

  • 1 is evaluated to 1.
  • 2 is evaluated to 2.

As a result, the array subscript operation becomes:

<code class="javascript">[5, 6, 8, 7][2]</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!