algorithm

+ can be used either as a binary operator, such as a + b, or as a unary operator, such as +’3′.

Unary operator

Directly to the Number type, equivalent to Number(). There are commonly used! Operator used to convert to Boolean type.

Binary operator

Let’s take a plus B for example

  1. Convert a and b to their original values (ToPrimitive) A1, b1
  2. If either A1 or b1 is a string, they are converted to string summation
  3. Otherwise, a1 and b1 are converted to number and added
The ToPrimitive(obj,preferredType) function takes two arguments, the first obj to the converted object and the second preferredType to the type you want to convert it to (null by default, When ToPrimitive(obj,preferredType) is executed, if the second parameter is null and obj is an instance of Date, the preferredType will be set to String. Otherwise, the preferredType is set to Number. If the preferredType is Number, ToPrimitive executes as follows: Otherwise, call obj.valueof () and return the original value if the result is executed. Otherwise, call obj.toString() and return it if the result is the original value; Otherwise, an exception is thrown. If the preferredType is String, switch steps 2 and 3 above, that is, if obj is the original value, return it; Otherwise, call obj.toString() and return it if the result is the original value; Otherwise, call obj.valueof () and return the original value if the result is executed. Otherwise, an exception is thrown.Copy the code

{} + [] = 0 and [] + {} = ‘[object object]’

Began to {{} + [] when statements will be JS interpreter when considered a code block, so the operation is essentially + [], an empty array to Number, 0

[] + {} use ToPrimitive method, [] to ”, {} to [object object], finally add [object object].