javascript - map() 函数内的索引

标签 javascript functional-programming immutable.js

我错过了如何获取 map 中的索引号的选项函数使用 List来自 Immutable.js :

var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();

Documentation showsmap()返回 Iterable<number, M> .有什么优雅的方法可以满足我的需要吗?

最佳答案

您将能够通过其第二个参数为 map 方法获取当前迭代的 index

示例:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

输出:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

另见: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

关于javascript - map() 函数内的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364400/

相关文章:

javascript - react radio 输入不检查

functional-programming - ImmutableJS vs Ramda 或 ImmutableJS + Ramda - 它们可以一起使用吗

javascript - 禁止用户更改浏览器选项卡

javascript - 将 html 内容调用到 jQuery 变量中

java - Functional Java - whenComplete 和 exceptionally 之间的交互

R:它能走多远? (加上通风)

ios - Swift 函数式编程 - 有没有比两个 map 调用更好的方法来翻译嵌套的 for 循环

javascript - 如何在类似 Om 的不可变应用程序状态中对关系数据建模

javascript - 如何从不可变树中获取更改的树,最大限度地重用节点

javascript - 在 "display:table-cell"之间填充