Monday, 24 July 2017

JavaScript array to number











I'm wondering something for few days...I know that unary plus in JavaScript first converts it's operand to Number. I'm applying + to an empty array and I get the following result:



+[] == 0


When I do this:



+[1] == 1



But:



+[1,2] == NaN


The last two things are almost clear but why the empty array is 0?!
Is this connected with:



[] == false



Some times ECMAScript makes me wonder a lot...



alert([![]+[]][+[]][+[]]+[![]+[]][+[]][+!+[]]+[!+[]+[]][+![]][+![]]+[![]+[]][+[]][+!+[]]+[![]+[]][+[]][+!+[]+!+[]]+' '+(![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]);


Best regards!


Answer



The stringified form of the empty Array is an empty string:




> [].toString()
""


The unary operator + converts to Number objects, so, it converts an empty string to 0:



> Number("")
0



This explains why +[] == 0 is true.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...