Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is .map() doing in this situation?

Tags:

javascript

Using the Chrome Console, this is my input and output:

[0].map(Array);  [[0, 0, [0]]]; // output 

What is happening here?

EDIT

The reason this makes me curious is because something like

[0].map(String); 

Will return

["0"]; 

And not

["0", "0", "String"] 
like image 633
Jacksonkr Avatar asked Sep 15 '17 00:09

Jacksonkr


People also ask

What is map () in JavaScript?

Definition and Usage. map() 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.

How do you use the map function?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable.

What does map return in JavaScript?

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

What is map function ES6?

ES6 - Array Method map() map() method creates a new array with the results of calling a provided function on every element in this array.


2 Answers

The .map() function is calling the Array() function with three arguments, the value of the array element which is 0, the index of that element, also 0, and a reference to the whole array.

So it's like doing this:

var a = [0]; var index = 0 Array(a[index], index, a);   // create array with three elements 

The array returned by Array() then becomes the first element of the array that .map() creates, hence the extra level of nesting in your [[0, 0, [0]]] result.

EDIT regarding your edit: when you say [0].map(String); that results in String() being called with the same three arguments like String(a[index], index, a), but the String() function ignores all but the first argument, whereas Array() uses all supplied arguments.

like image 127
nnnnnn Avatar answered Oct 23 '22 13:10

nnnnnn


Firstly, Array could be used as a function to create arrays:

var arr = Array(1, 2, "Hello");    console.log(arr); // [1, 2, "Hello"]

Secondly, map passes three parameters to its callback: the element, its index from the array and the array itself.

So, since your array contains one element, the line:

[0].map(Array); 

is equivalent to:

[Array(0, 0, [0])];     // the element 0 in the original array will be mapped into Array(0, 0, [0]) 
like image 24
ibrahim mahrir Avatar answered Oct 23 '22 14:10

ibrahim mahrir