JavaScript Array#map:索引参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26371083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Array#map: index argument
提问by Claudio
My question is about the mapmethod of arrays in JavaScript.
我的问题是关于mapJavaScript 中数组的方法。
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?
你会用这个功能做什么?
回答by Guffa
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
回答by Tim Jansen
Sometimes the index of the element matters. For example, this map replaces every second element with 0:
有时元素的索引很重要。例如,此映射将每隔一个元素替换为 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]
回答by kapex
Here is a description of of the mapfunction:
下面是map函数的描述:
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.
callback
生成新数组元素的函数,采用三个参数:
currentValue
数组中正在处理的当前元素。
index
数组中正在处理的当前元素的索引。
array
调用了数组映射。
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.
map 函数将回调函数作为参数(而不是索引作为参数,正如在编辑之前的问题中最初所述)。回调函数有一个索引作为参数——回调是自动调用的,所以你不需要自己提供索引。如果您只需要当前值,则可以省略其他参数。

