首页 > 解决方案 > array.map() - currentValue and index parameters switched?

问题描述

I am pulling an input elements array from the DOM using the the id and using .map() to loop through the array. My code works, however currentValue and index are switched:

ports = $("#edit_display_control_ports > li > input").map(function(currentValue, index){ 
  return index.value;}
).toArray(); 

Again, this code works. According to documentation, the first parameter of the map() function should be the currentValue and the second, index. However I have to switch the two. The currentValue return the index of the array, while the index parameter returns the element.

标签: javascriptarraysdictionary

解决方案


您部分正确,您的问题是您没有运行 javascript 的 native .map,这是 jQuerys .map,因为您在 jQuery 集合上调用它。

jQuery 的地图工作方式不同:

回调类型:Function(Object elementOfArray, Integer indexInArray) => Object 处理每个项目的函数。函数的第一个参数是数组项,第二个参数是数组中的索引 函数可以返回任何值。返回的数组将被展平为结果数组。在函数中,this 指的是全局(窗口)对象。

看看这里


推荐阅读