Array self-referential map - a very unusual result

While experimenting with some different methods of generating JavaScript arrays, I came across a strange result. Using map to push 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 someone explain why?

+4
source share
2 answers

For each element in a , push , the index of that element, and the array passed through are called with this element. For each element of the array, we add these three additional elements. This means that the length is increased by three for each element in the original array. The result of push is the length of the array after adding elements, so the resulting array (from map ) is an array containing the lengths of the array a after each push callback is complete.

See the documentation for map and push .

+5
source

This is because the return value of push is the new length. Not sure why it is increasing by 3.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push

Returns
The new length property of the object on which the method was called.

+1
source

All Articles