JavaScript Array#map: index argument

2020-05-19 15:48发布

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?

3条回答
够拽才男人
2楼-- · 2020-05-19 16:34

Sometimes the index of the element matters. For example, this map replaces every second element with 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]
查看更多
时光不老,我们不散
3楼-- · 2020-05-19 16:38

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/

查看更多
三岁会撩人
4楼-- · 2020-05-19 16:44

Here is a description of of the map function:

arr.map(callback[, thisArg])

callback
Function that produces an element of the new Array, taking three arguments:

currentValue
The current element being processed in the array.

index
The index of the current element being processed in the array.

array
The array map was called upon.

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

查看更多
登录 后发表回答