LoginSignup
11
6

More than 3 years have passed since last update.

【JavaScript】forEach,mapメソッドの違い、使いどころ

Last updated at Posted at 2020-05-01

【JavaScript】forEach,mapメソッドの違い、使いどころ

forEach(),map()の違い、使いどころを整理しました。

forEach

引数それぞれ(=each)に同じ処理を実行する。
使いどころ:for文よりも短く書きたい場合。


    const a=[0,1,2,3];

    a.forEach((tempA)=>{     //aの要素を受けとるtempAという入れ物を作る
        return tempA += 1;    //tempAに対して1ずつ加算
        })

    console.log(a);             //[1,2,3,4]

map

配列に同じ処理を関連付けして(=map)、新しい配列を作る。
使いどころ:元の配列を残したまま、新しい配列を作るとき(比較、行列的な処理?)

    const a = [0,1,2,3];
    const b = a.map((tempA)=>{ //配列aを基に配列bを作成
        return tempA + 1;       //tempAに対して1ずつ加算
    })

    console.log(b);       //[1,2,3,4]

短く書くために

forEach()もmap()もfor文に比べると短く書けるのが利点。
アロー関数の場合、次の条件を満たせば更に短く書くことができる。

・引数が1つの場合()を省略可能
・return行が1行の場合{return}を省略可能

私はグルーピングする要素()とか{}が1つの場合=省略できると覚えました。

forEach文を省略しない場合


    a.forEach((tempA)=>{
        return tempA += 1;
        })

forEach文を省略した場合

    a.forEach(tempA=> tempA += 1)

map文を省略しない場合

    const b = a.map((tempA)=>{
        return tempA + 1;
    })

map文を省略した場合


    const b = a.map(tempA=> tempA + 1);
11
6
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
11
6