Was messing around with some array stuff earlier and discovered a very peculiar caveat
consider this code:
[1,2,3].map(function(el) { return el * 2}).push(4*2).join(" ");
In writing it, I expected to get: 2, 4, 6, 8
instead, it threw an exception. in investigating further, the .push
returns the adjusted .length
of the passed array:
[1,2,3].map(function(el) { return el * 2}).push(4*2);
>>> 4
[1开发者_JS百科,2,3,4].map(function(el) { return el * 2}).push("hi");
>>> 5
and typeof is number, so the .join
throws as it's not in the number proto.
it seems you can pass on / chain any other array methods but not push. though this is not a problem and it works if you pass on the result into a variable, why is breaking as is and why is the length property being returned here?
this works fine...
var foo = [1,2,3,4].map(function(el) { return el * 2});
foo.push(5*2);
console.log(foo);
>>> [2, 4, 6, 8, 10];
probably another wtfjs moment...
Why is the length property being returned here?
It is defined in the specification:
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
Why is breaking as is?
Well, you answered this already yourself: .push
returns the new length and .join
is not defined for numbers.
精彩评论