Подтвердить что ты не робот

Функция индекса внутри карты()

Мне не хватает опции, чтобы получить номер индекса внутри функции map, используя List из Immutable.js:

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

Документация показывает, что map() возвращает Iterable<number, M>. Есть ли какой-либо элегантный способ для того, что мне нужно?

4b9b3361

Ответ 1

Вы сможете получить текущую итерацию index для метода 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

Parameters

обратный вызов -   Функция, которая создает элемент нового массива, принимая три аргумента:

1) currentValue
      Текущий элемент, обрабатываемый в массиве.

2) индекс
    Индекс текущего элемента, обрабатываемого в массиве.

3) массив
    Карта массива была вызвана.

Ответ 2

Индекс Array.prototype.map():

Доступ к индексу Array.prototype.map() можно получить через второй аргумент функции обратного вызова. Вот пример:

const array = [1, 2, 3, 4];


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

console.log(map);

Ответ 3

Использование Рамды:

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