JavaScript Array #map:index参数

Cla*_*dio 49 javascript methods map

我的问题是关于mapJavaScript中的数组方法.

你可以传递一个函数,它接受第二个参数,正在处理的数组的当前元素的索引,但是...到什么目的?当你这样做时会发生什么,而当你不这样做时会有什么不同?

您将使用此功能?

Guf*_*ffa 93

当前项的索引始终传递给回调函数,唯一的区别是,如果您未在函数中声明它,则无法通过名称访问它.

例:

[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;
});
Run Code Online (Sandbox Code Playgroud)

输出:

0
1
2
0
1
2
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/Guffa/k4x5vfzj/


Tim*_*sen 14

有时元素的索引很重要.例如,此映射将每个第二个元素替换为0:

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

输出:

[1, 0, 3, 0, 5, 0]
Run Code Online (Sandbox Code Playgroud)


kap*_*pex 6

以下是该map功能的说明:

arr.map(callback[, thisArg])
Run Code Online (Sandbox Code Playgroud)

callback
产生新数组元素的函数,带有三个参数:

currentValue
当前元素在数组中处理.

index
数组中正在处理的当前元素的索引.

array
调用了数组映射.

map函数将回调函数作为参数(而不是索引作为参数,如在编辑之前在问题中最初所述).回调函数有一个索引作为参数 - 回调是自动调用的,因此您不需要自己提供索引.如果只需要当前值,则可以省略其他参数.