This happens because [] is
            coerced to 0.
You can see this
            with the following call:
(new
            Number([])).valueOf(); //
            0
Therefore, calling
            Math.min([]) is the same as calling
            Math.min(0) which gives
            0.
I
            believe that the reason that new Number([]) treats
            [] as 0 is
            because:
- The             href="http://www.ecma-international.org/ecma-262/6.0/#sec-number-constructor-number-value"
 rel="nofollow noreferrer">spec for theNumber(value)
 constructor uses aToNumber
 function.
- The             href="http://www.ecma-international.org/ecma-262/6.0/#sec-tonumber" rel="nofollow
 noreferrer">spec for theToNumber(value)function
 says to useToPrimitivefor anobject
 type (which an array is).
- The primitive value of an array
 is equal to having the array joined, e.g.[]becomes
 "",[0]becomes
 "0"and[0, 1]becomes
 "0,1".
- The number constructor
 therefore converts[]into""which is
 then parsed as
 0.
The
            above behaviour is the reason that an array with one or two numbers inside it can be
            passed into Math.min(...), but an array of more
            cannot:
- Math.min([])
 is equal to- Math.min("")or
 - Math.min(0)
- Math.min([1])
 is equal to- Math.min("1")or
 - Math.min(1)
- Math.min([1,is equal to
 2])- Math.min("1,2")which cannot be
 converted to a number.
 
No comments:
Post a Comment