Maison > interface Web > js tutoriel > le corps du texte

Pourquoi « [[]][ []] [ []] » est-il égal à 10 en JavaScript ?

Barbara Streisand
Libérer: 2024-11-15 10:29:02
original
617 Les gens l'ont consulté

Why does

Exploring the Enigma of "++[[]][+[]]+[+[]]" in JavaScript

JavaScript developers may find themselves stumped by the expression "++[[]][+[]]+[+[]]" as it yields the unexpected result of "10". Let's delve into the process behind this enigmatic calculation to unravel its intricacies.

Breaking It Down

If we break down the expression, it reads as follows:

++[[]][+[]]
+
[+[]]
Copier après la connexion

In JavaScript, array elements can be coerced into numbers using the '+' operator. Specifically, +[] === 0. This coerces arrays into empty strings, resulting in +"" === 0.

Simplifying the Computation

With this understanding, we can simplify the expression as:

++[[]][0]
+
[0]
Copier après la connexion

Accessing the first element of an array, [[]][0], returns the inner array. Due to references, we'll refer to it as A to avoid confusion.

Incrementing and Converting

The ++ operator increments its operand by one and returns the incremented result. Therefore, ++[[]][0] is equivalent to Number(A) + 1.

String Concatenation

We can further simplify:

(+[] + 1)
+
[0]
Copier après la connexion

First, [] is coerced into the string "0". Then, +[] results in 1. Finally, "1" is concatenated with "0" using +, as arrays can be joined with , resulting in 10.

Technicalities

Behind the scenes, the process of coercing +[] into 0 involves several specification references:

  • Unary + Operator: Converts its operand to a number, coercing it into a string ("") first.
  • Number Conversion (ToNumber()): Coerces the array ([]) into a string ("").
  • Primitive Value Conversion (ToPrimitive()): In String mode, uses the object's [[DefaultValue]] method.
  • [[DefaultValue]]: Calls the [[Get]] method with argument "toString".
  • Array's toString Method: Invokes the [[Join]] method, which yields "" for [].

Conclusion

Through this step-by-step analysis, we have shed light on the mechanics behind the baffling expression "++[[]][+[]]+[+[]]" in JavaScript. Its execution involves coercion, incrementation, and concatenation, ultimately revealing the logical journey that leads to the surprising result of "10".

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal