From a question ++[[]][+[]]+[+[]], thinking about implicit types

I found a similar question on the Internet.
Q: Why does! +[]+[] result in 4?
js is a weakly typed language, and the implicit
conversion rules in js are:

  1. If one of the operands is a string, the other operand is implicitly converted to a string, and then the string is concatenated to obtain the result.
  2. If the operand is a complex data type such as an object ({}) or an array ([]), then both operands are converted to strings and spliced

String([]) //[] The result of string conversion is ""
String({}) //{} The result of string conversion is "[object Object]"

  1. If the operand is a simple data type like boolean, then convert the operand to number and add the result

Therefore, the calculation process of !+[]+[] is
to calculate first!+[], and convert [] to "", which is equivalent to calculating !+"", and the result is !"",!""=true. After the calculation, +[] is equivalent to true+[], which is true+""='true', and finally the string'true'.length = 4
can be obtained here, when the data type of boolean and the array type of [] When using + to connect, the two parties are directly converted to the string type, and then the string is spliced.
When the two boolean types are connected with +, they are both converted to the number type and added together to get the result.

——————————————————

The corresponding ++[[]][+[]]+[+[]] calculation process is:
calculate the right part:
[+[]], which is [+""], which is [+false], which is [+0 ], ie [0]
Insert picture description here
is the object type (array to be precise)

Calculate the left part:
++[[]][+[]], which can be converted to ++[[]][0]
[[]] is such a thing as [0: []], so it The 0 item of is []
++ self-increment. When the string contains valid numbers, first convert it to a digital value, and then perform the addition of 1
Number([ ]) is 0, and the final result on the left part is 1 of the number type.

1+[0], that is, 10
complex data types of string type will be converted to String first, and then converted to Number operation during implicit conversion
Insert picture description here

https://www.cnblogs.com/ziyunfei/archive/2012/09/15/2685885.html
This blog post explains []+[ ],[ ]+{},{}+[ ],{}+{ }What is the output of the four cases

Guess you like

Origin blog.csdn.net/s8806479/article/details/114598108