Adding Empty Array With Empty Object Yields Different Results When Flipping Operands
Best way to describe my question is to illustrate by example : # node v4.3.1 > {} + [] 0 > [] + {} '[object Object]' > [] + {} === {} + [] true I have managed to find a W
Solution 1:
Case {} + []:
JavaScript thinks {} is an empty block statement and it's just ignored. Then + [] -> + '' -> + 0 -> 0.
The empty block statement is converted to object literal this way: ({}), so the fixed version should be: ({}) + [].
Case [] + {}:
[] + {} -> '' + '[object Object]' -> "[object Object]".
Case [] + {} === {} + []:
[] + {} === {} + [] -> '' + '[object Object]' === '[object Object]' + '' -> '[object Object]' === '[object Object]' -> true
Notice:
- An array is transformed to a primitive value using
toString()method, which is actually anjoin(',').[]is transformed to a primitive with[].join(',')->'' - The regular
Objectis transformed to a primitive value usingtoString()too, which by default returns[object Object] <value> + <value2>operator tries to transform it's operands to primitive values. Then tries to concatenate the result of transformation+ <value>operator transforms the operator to primitive value, then the result is converted to anumber
Post a Comment for "Adding Empty Array With Empty Object Yields Different Results When Flipping Operands"