Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 46456  / 10 Years ago, tue, october 14, 2014, 12:00:00

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?


More From » methods

 Answers
22

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/


[#69120] Monday, October 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;