LoginSignup
78
67

More than 3 years have passed since last update.

【JavaScript】map関数を用いたおしゃれな配列処理

Posted at

はじめに

決まった繰り返し処理といえばforですが、JavaScriptのES6以降ではmap関数を使ってもっと簡単でおしゃれな書き方で書けます。

map関数は各要素に対して決まった繰り返し処理をして、新しい配列を生成するのに使える便利な関数です

例として、[1,2,3,4,5,6]といったような各要素を二乗した配列を作ることを考えます。

通常のfor文から書き換え

まずは通常のfor文で書いてみます。


const list = [1,2,3,4,5,6];
const newList = [];

for(let i = 0; i< list.length ; i++){
    newList[i] = list[i]*list[i];
}

console.log(newList); //[1,4,9,16,25,36]

list[i]が煩わしい気がします。
これをforEach文で書き直すとこうなります。


const list = [1,2,3,4,5,6];
const newList = [];

list.forEach(function(item, index){
  newList[index] = item*item;
}

console.log(newList);

newListの宣言が煩わしい気がします。
これをmapで修正するとこうなります。


const list = [1,2,3,4,5,6];

const newList = list.map(function(item){
    return item*item;
});

console.log(newList) //[1,4,9,16,25,36]

returnされたものが新しい配列の要素一つになります。

新しい配列はlistから生成するんだ」ということが一瞬で伝わって、非常にすっきり書けていますね。
自分自身を更新(して複製)」する時にMapは便利です。

これを使うとReactのDOMを複数生成するのに便利だったりします。

参考

この記事は「CodeShip」内での実際の質疑応答や指導・アドバイスの一部を基に作成しています。

78
67
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
78
67