Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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... to what purpose? What happens when you do it and what's the difference when you don't?

What would you use this feature for?

like image 226
Claudio Avatar asked Oct 14 '14 21:10

Claudio


People also ask

What is an array in JavaScript?

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.

How do you write an array in JavaScript?

An array can be created using array literal or Array constructor syntax. Array literal syntax: var stringArray = ["one", "two", "three"]; Array constructor syntax: var numericArray = new Array(3); A single array can store values of different data types.


1 Answers

The index of the current item is always passed to the callback function, the only difference if you don't declare it in the function is that you can't 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's still there     return 0; }); 

Output:

0 1 2 0 1 2 

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

like image 107
Guffa Avatar answered Oct 19 '22 09:10

Guffa