7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptのarrayのmap関数でアロー関数を使う

Posted at

##arrayのmap関数とは?
「配列内のすべての要素に対して、同じ処理を加えた新しい配列を返す」関数。

サンプル

array1 = [0,1,2,3,4,5]

という配列に対して、すべての要素を2倍にした新しい配列

array2 = [0,2,4,6,8,10]

を簡単に作れる

###map関数の基本的な使い方の例

サンプル

var func = function nibai(value){return value * 2};

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map(func);
console.log(newArray); // =>[2,4,6,8,10]
  1. 引数を一つ取り、引数を二倍にして返すnibai関数を作り、変数funcに代入する
  2. baseArrayを作る
  3. baseArrayのmapメソッドを使い、引数として1で作った関数(を代入した変数func)を渡す
  4. mapメソッドが、配列の中身を一つづつnibai関数に渡して結果を受け取る
  5. すべての値が二倍になった配列が得られる

###無名関数を使う
サンプル

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map(function(value){return value * 2});
console.log(newArray); // =>[2,4,6,8,10]

###アロー関数を使う

1 : 通常の書き方

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map(function(value){return value * 2});
console.log(newArray); // =>[2,4,6,8,10]

2 : アローを使って「function」を省略

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map((value) => {return value * 2});
console.log(newArray); // =>[2,4,6,8,10]

3 : 1行ならreturnと{}を省略可能

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map((value) => value * 2);
console.log(newArray); // =>[2,4,6,8,10]

4 : 引数1個なら()も省略可能

var baseArray = [1,2,3,4,5];
var newArray = baseArray.map(value => value * 2);
console.log(newArray); // =>[2,4,6,8,10]
7
9
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
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?