JavaScript Array#map: index argument

前端 未结 3 1394
夕颜
夕颜 2021-02-02 06:15

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 th

3条回答
  •  無奈伤痛
    2021-02-02 06:22

    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]
    

提交回复
热议问题