js magic "+" operation

As we all know, js is a weak language. Unlike Java, you must declare the type of the variable when you define a variable. Usually, when we use the'+' operation, we just add numbers or spell them into strings, but there are also Some surprises, such as:
1. Let’s start with a simple one:

 true+true

Printed out is 2, the reason is that js will convert true to the number 1 and false to 0 when it is executed;

2. Another pervert:

[3,4]+[5,6]=?

If you know the principle of children's shoes will tell me the answer is: 3,45,6, why is this?
The reason is simple: First of all, let's talk about the data types of js. The basic types are undefined, null, number, string, boolean, and the complex data types Array and Object. When we perform the "+" operation:
A: If it is a number addition, the normal addition operation will be performed;
B: If one of the addends is a non-digit, then it will be converted to string type for string splicing;
C: If it is a complex type, Array will use the string() method to convert the array to the corresponding string. If it is an empty Array, it will be ". If it is a non-empty array, for example, [5,6] will be converted to '5. ,6'; if it is an object, it will return'[object Object]' after calling the string method;
so [3,4]+[5,6]='3,4'+'5,6'=3,45, 6
3. Upgraded abnormal:

{a:4}+[5,6]=?

According to the calculation method above, we can quickly conclude that it is [object Object]5,6
{a:4}+[5,6]='[object Object]'+'5,6'=[object Object]5 ,6
4 Let's look at a group of disgusting additions:

[]+{}=?
{}+[]=?

If you print it out, you will find that the first one is'[object Object]', which is in line with our calculation logic, but the second one becomes '0' (some browsers are normally'[object Object]'). As for What is the reason for 0? When the first {} is executed again, the browser will treat it as a statement (declaration), the real execution is +[], when +[], it will pass Number ([]) to 0
5. What if two empty objects are added together?

{}+{}=?

The execution result of some browsers is'[object Object][object Object]', and some execution results are NaN. If it is NaN, the execution process is similar to point 5, which is equivalent to executing +Number({}) , So the result is NaN.

Summary:
1. number+number=addition operation such as 2+3=5
2.number+String or string+string=string splicing; 1+'a'='1a'
3.Array+Object=string(Array)+ string(Object)
4.{}+any=Number(any)

Guess you like

Origin blog.csdn.net/weixin_43169949/article/details/95016829