map() 関数内のインデックス 質問する

map() 関数内のインデックス 質問する

frommapを使用して関数内のインデックス番号を取得するオプションがありません:ListImmutable.js

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

ドキュメントにはmap()返しますIterable<number, M>。必要なものを得るためのエレガントな方法はありますか?

ベストアンサー1

index2 番目のパラメータを通じて、メソッドの現在の反復を取得できます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

パラメーター

callback - 3 つの引数を取り、新しい配列の要素を生成する関数:

  1. currentValue
    配列内で現在処理されている要素。

2) インデックス
配列内で現在処理されている要素のインデックス。

  1. 配列
    配列マップが呼び出されました。

おすすめ記事