我错过了一个选项,如何从Immutable.js中使用List在map函数中获取索引号:

Var list2 = list1。映射(mapper => {a:映射器。A, b: mapper.index??}) .toList ();

文档显示map()返回Iterable<number, M>。有什么优雅的方式能满足我的需求吗?


当前回答

使用Ramda:

import {addIndex, map} from 'ramda';

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

其他回答

您将能够通过map方法的第二个参数获得当前迭代的索引。

例子:

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

参数 回调, 函数,该函数产生一个新数组的元素,有三个参数: 1) currentValue 数组中正在处理的当前元素。 2)指数 数组中正在处理的当前元素的索引。 3)数组 调用了数组映射。

Array.prototype.map()指数:

可以通过回调函数的第二个参数访问索引Array.prototype.map()。这里有一个例子:

Const数组= [1,2,3,4]; Const map = array。Map ((x, index) => { console.log(指数); 返回x + index; }); console.log(地图);

Array.prototype.map()的其他参数:

回调函数的第三个参数公开了调用map的数组 Array.map()的第二个参数是一个对象,它将是回调函数的this值。请记住,为了声明回调,必须使用常规的function关键字,因为箭头函数没有自己与this关键字的绑定。

例如:

Const数组= [1,2,3,4]; const thisObj = {prop1: 1} Const map = array。Map ((x, index, array) => { console.log(数组); console.log(这) }, thisObj);

假设你有一个数组

Const arr = [1, 2, 3, 4, 5, 6, 7, 8,9] 加勒比海盗。map((myArr, index) => { console.log('您的索引是-> ${index} AND值是${myArr} '); })

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

使用Ramda:

import {addIndex, map} from 'ramda';

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