JavaScript Array#map: index argument

前端 未结 3 1374
夕颜
夕颜 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:41

    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/

提交回复
热议问题