Reputation: 56769
While experimenting with some different methods for generating JavaScript arrays, I stumbled on a weird result. Using map
to push
an array of self-references (DEMO):
a=[1,1,1,1,1,1,1,1,1,1];
a=a.map(a.push,a);
I get the following result (in Chrome):
[13,16,19,22,25,28,31,34,37,40]
Can anyone explain why?
Upvotes: 5
Views: 822
Reputation: 532455
For each element in a
, push
is being called with that element, the index of that element, and the array being traversed. For each element in the array, then, we add these three additional elements. This accounts for the length increasing by three for each element in the original array. The result of push is the length of the array after the elements are added, thus the resulting array (from map
) is an array holding the lengths of the a
array after each push callback is completed.
See the documentation for map and push.
Upvotes: 6
Reputation: 137292
It has something to do with the return value of push
being the new length. Not sure why it incrementing by 3.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push
Returns
The new length property of the object upon which the method was called.
Upvotes: 2