JavaScript Array # map: index argument

My question is about the map method of arrays in JavaScript.

You can pass it a function that takes a second argument, the index of the current element of the array being processed, but ... for what purpose? What happens when you do this and what's the difference when you don't?

What would you use this function for?

+47
javascript methods map
Oct 14 '14 at 21:57
source share
3 answers

The index of the current element is always passed to the callback function, the only difference if you do not declare it in the function is that you cannot access it by name.

Example:

 [1,2,3].map(function(o, i){ console.log(i); return 0; }); [1,2,3].map(function(o){ console.log(arguments[1]); // it still there return 0; }); 

Output:

 0 1 2 0 1 2 

Demo: http://jsfiddle.net/Guffa/k4x5vfzj/

+89
Oct. 14 '14 at 10:07
source share
— -

Sometimes the index of an element matters. For example, this card replaces every second element 0:

 var a = [1, 2, 3, 4, 5, 6]; var b = a.map(function(el, index) { return index % 2 ? 0 : el; }); console.log(b); 

Output:

 [1, 0, 3, 0, 5, 0] 
+12
Oct 14 '14 at 22:01
source share

The following is a description of the map function:

 arr.map(callback[, thisArg]) 

callback
A function that creates an element of a new array using three arguments:

currentValue
The current item is processed in an array.

index
The index of the current item is processed in the array.

array
An array map has been called up.

The map function takes a callback function as an argument (and not as an index as an argument, as originally stated in the question before editing it). The callback function has an index as a parameter - the callback is called automatically, so you do not provide the index yourself. If you only need the current value, you can omit other parameters.

+6
Oct. 14 '14 at 10:01
source share



All Articles