首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Index map map()函数

Index map map()函数
EN

Stack Overflow用户
提问于 2016-07-14 02:07:22
回答 4查看 714.1K关注 0票数 519

我遗漏了一个选项,即如何使用map函数中的ListImmutable.js获取索引号

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-07-14 02:18:09

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

示例:

代码语言:javascript
复制
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]
});

输出:

代码语言:javascript
复制
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

也请参阅: 对象/数组/地图

参数 回调函数,它生成新数组的一个元素,包含三个参数: 1) currentValue 正在数组中处理的当前元素。 2)索引 数组中正在处理的当前元素的索引. 3)阵列 调用了数组映射。

票数 897
EN

Stack Overflow用户

发布于 2018-10-29 18:21:37

Array.prototype.map()指数:

可以通过回调函数的第二个参数访问索引Array.prototype.map()。下面是一个示例:

代码语言:javascript
复制
const array = [1, 2, 3, 4];

const map = array.map((x, index) => {
  console.log(index);
  return x + index;
});

console.log(map);

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

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

例如:

代码语言:javascript
复制
const array = [1, 2, 3, 4];

const thisObj = { prop1: 1 }

const map = array.map((x, index, array) => {
  console.log(array);
  console.log(this)
}, thisObj);

票数 67
EN

Stack Overflow用户

发布于 2020-11-28 03:52:13

  • 假设您有一个数组,如

代码语言:javascript
复制
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })

代码语言:javascript
复制
> 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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38364400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档