Why does 5,6,8,7 = 8 in JavaScript?
This peculiar behavior in JavaScript has puzzled many developers. Let's delve into the inner workings of JavaScript expressions to understand why this occurs.
As you've noticed, the following operation returns 4:
This is because the second set of brackets represents an array subscript operation, where the index is the expression 1,2,3. However, when the second set of brackets is [1,2], the result is 3.
The key to understanding this is to realize that the second [...] cannot be an array. Instead, it is an array subscript operation. The contents of a subscript operation are not a delimited list of operands but a single expression.
In this case, the expression is 1,2, which evaluates to 2. Therefore, the subscript operation [1,2] is equivalent to [2], which returns the element at the index 2 in the first array. This element is the number 8.
In summary, the expression [5,6,8,7][1,2] is equivalent to [5,6,8,7][2], which returns the element at the index 2 in the first array, which is 8.
The above is the detailed content of Why does `[5,6,8,7][1,2]` equal 8 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!