Why does Math.min([]) evaluate to 0?
This question already has an answer here:
Why does Math.min([])
evaluate to 0
?
Because the spec says so:
Math.min
casts each parameter to a number using...
ToNumber
casts objects to a number using...
ToPrimitive
casts objects to primitive values using...
[[Default Value]]
internal method converts objects to primitives based on their hint parameter.
The default hint for all objects is string. Which means the array gets converted to a string, which for []
is ""
.
ToNumber
then converts ""
to 0
, per the documented algorithm
Math.min
then takes the only parameter and returns it, per its algorithm.
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:
Number(value)
constructor uses a ToNumber
function. ToNumber(value)
function says to use ToPrimitive
for an object
type (which an array is). []
becomes ""
, [0]
becomes "0"
and [0, 1]
becomes "0,1"
. []
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, 2])
is equal to Math.min("1,2")
which cannot be converted to a number. 上一篇: JavaScript数组编号