Symbol.toPrimitive is a built-in Symbol value that exists as a function value attribute of an object and is called when an object is converted to its original value.
An object can be converted to its original value with the help of the symbol.toprimitive property, which is used as a function value. When called, the function is passed a string parameter hint indicating the expected type of the original value to be converted to.
The hint parameter can take any of “number”, “string”, or “default”. The conversion process is as follows
Val.valueof () → val.toString() → error
String: val → val.toString() → val.valueof () → error
Default: the same number
Var obj1 = {}; var obj1 = {}; console.log(+obj1); // NaN console.log(`${obj1}`); // "[object Object]"
console.log(obj1 + ""); // "[object Object]"Var obj2 = {[symbol.toprimitive](hint) {var obj2 = {[symbol.toprimitive](hint) {if (hint == "number") {
return 10;
}
if (hint == "string") {
return "hello";
}
return true; }}; console.log(+obj2); // 10 -- hint parameter value is"number"
console.log(`${obj2}`); // "hello"The hint parameter value is"string"
console.log(obj2 + ""); // "true"The hint parameter value is"default"
Copy the code
Addition operation in JS
1. Use ToPrimitive to convert the left and right elements ToPrimitive (primitive).
2. After the conversion, if one of the operands has a value whose original data type is “string”, the other operand is cast to a string and then performs string concatenation.
3. In other cases, all operands are converted to a “numeric” value of the original data type and then added to the numbers.
Then let’s look at [] + {} == {} + []
1, {} + [] == 0
Actually {} is just a block of code
{} + [] =>
+ [] =>
+ ([]).valueOf() =>
+ ""= > 0Copy the code
[] + {} == “[object object]”
([]).valueOf() + ({}).valueOf() =>
[] + {} =>
([]).toString() + ({}).toString =>
"" + "[object Object]"= >"[object Object]"
Copy the code
3, [] + {} == {} + []
[object object] == “[object object]”
4、{} + [] != [] + {}
注:chrome 中 {} + [] == [] + {}
{} + [] != [] + {} =>
+ [] != [] + {} =>
0 != "[object Object]"
Copy the code
Reference:
Symbol.toPrimitive
JS addition operations are fully parsed