简体   繁体   中英

Why is Number([]) === 0 and Number({}) === NaN in Javascript?

I was looking at the first table on http://zero.milosz.ca/ , and wanted to understand why, for example, 0 == [] and 0 != {} . I'm assuming it's because Number([]) == 0 and Number({}) == NaN . However, that part seems arbitrary. Why is an empty list 0 and empty object a NaN ?

Using Number(some_object) will use the string representation of the given object. For your examples the string representations are:

js> ({}).toString();
[object Object]
js> [].toString();

js>

The string '[object Object]' cannot be converted to a number but the empty string '' can.

To elaborate a bit on ThiefMaster's answer, I've taken a look into ECMAScript's specifications :

When converting a string into a number, a grammar is used for the conversion. In particular, the mathematical value of StringNumericLiteral ::: [empty] is defined as 0. In fact, it's 0 for any whitespace.

When one value is an object ([],{}) and the other is a number or string, operator == converts the object to a primitive value (a number in this case) using the built-in conversion methods which all objects in Javascript inherit: toString() and valueOf() .

For generic objects like {}, valueOf is used, and by default it returns the object itself, which is != 0.

For built-in arrays, toString is used. This method applied to an array returns a string containing all the elements joined by commas. For the empty array, it returns an empty string, ''.

Then the interpreter applies valueOf to that string; the return value of this method for an empty string is 0, so [] == 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM