Closed wjm1314 closed 5 years ago
The join
is actually perfectly expected. You're joining array elements into a string so it triggers toString
for each element.
The +
is also expected, although a bit less, the thing is that +
is primarily an arithmetic operator so it triggers valueOf
, however the valueOf
a string primitive is that string primitive and since one of the values in the expression remained a string the +
falls back to being a concatenation operator. This can be seen as a bit WTF, however situations similar to that are covered in the Funny math section.
oh~~~, I got it! Thank you!
Example(Unexpected result):
var foo = { toString: function() { return 'foo'}, valueOf: function() { return 5} } console.log(foo + 'bar'); //5bar console.log([foo,'bar'].join('')); //foobar