【问题标题】:array.map() - currentValue and index parameters switched? [duplicate]array.map() - currentValue 和 index 参数切换? [复制]
【发布时间】:2019-10-24 15:19:43
【问题描述】:

我正在使用 id 从 DOM 中提取一个输入元素数组,并使用 .map() 循环遍历该数组。我的代码有效,但是 currentValue 和 index 被切换:

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

同样,此代码有效。根据文档,map() 函数的第一个参数应该是 currentValue,第二个参数应该是 index。但是我必须切换两者。 currentValue 返回数组的索引,而 index 参数返回元素。

【问题讨论】:

标签: javascript arrays dictionary


【解决方案1】:

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

jQuery 的地图工作方式不同:

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

看看here

【讨论】:

    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 2018-07-18
    • 2019-07-21
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多