本文介绍了map() 函数内的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我缺少如何使用 Immutable.js 中的 Listmap 函数中获取索引号的选项:

I am missing a option how to get the index number inside the map function using List from Immutable.js:

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

文档显示 map() 返回 Iterable.有什么优雅的方法可以满足我的需求吗?

Documentation shows that map() returns Iterable<number, M>. Is there any elegant way to what I need?

推荐答案

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

You will be able to get the current iteration's index for the map method through its 2nd parameter.

示例:

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("
");
  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

参数

回调 -生成新数组元素的函数,采用三个参数:

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

1) 当前值
数组中正在处理的当前元素.

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

2) 索引
数组中正在处理的当前元素的索引.

3) 数组
调用了数组映射.

3) array
The array map was called upon.

这篇关于map() 函数内的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 13:31
查看更多