JavaScript Array#map:index参数 [英] JavaScript Array#map: index argument

查看:136
本文介绍了JavaScript Array#map:index参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于JavaScript中数组的 map 方法。



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



你将会使用这个功能?

解决方案

当前项目的索引总是传递给回调函数,唯一的区别,如果你不在函数中声明它是你不能访问它



示例:

  [1,2,3] .map(function(o,i){
console.log(i);
return 0;
});

[1,2,3] .map(function(o){
console.log(arguments [1]); //它还在
return 0;
});

输出:

 code> 0 
1
2
0
1
2

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


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?

解决方案

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/

这篇关于JavaScript Array#map:index参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆