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?
The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .
Definition and Usagemap() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.
To create an Array from Map, we can use map. entries() method. let newIterable = map. entries(map); //return iterable with [key,value] pairs let newArray = Array.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With