map()函数内部的索引 [英] Index inside map() function

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

问题描述

我缺少一个选项,它使用 List 从<$ c获取 map 函数中的索引号$ c> Immutable.js :



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



Documentation shows map()返回 Iterable< number,M> 。有没有什么优雅的方式来满足我需要的?

解决方案

您将能够获得当前迭代 index map API通过其第二个参数指定

另请参阅: https://developer.mozilla.org/ docs / Web / JavaScript / Reference / Global_Objects / Array / map
$ b


参数



callback -
产生新数组元素的函数,带三个参数:


1)currentValue

当前在数组中处理的元素。



2)索引

索引在数组中处理当前元素。



<3>数组
调用数组映射。


示例:

  var list = ['h','e','l','l ','o']; 
list.map((currElement,index)=> {
console.log(Current iteration is:+ index);
console.log(当前元素是: + currElement);
console.log(\ n);
return'X';
});

输出:


当前迭代为:0
当前元素为:h



当前迭代为:1
当前元素是:e

当前迭代是:2
当前元素是:l


当前的迭代是:3
当前元素是:l

当前迭代是:4
当前元素是:o



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

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

解决方案

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

See also: 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.

Example:

var 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 'X';
});

Output:

The current iteration is: 0
The current element is: h

The current iteration is: 1
The current element is: e

The current iteration is: 2
The current element is: l

The current iteration is: 3
The current element is: l

The current iteration is: 4
The current element is: o

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆