0
1

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 5 years have passed since last update.

【Javascript】mapメソッドー学習ノート

0
Posted at

初めに

javascriptのmapメソッドについて学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

mapメソッド

配列の要素に対し、メソッド内で定義した関数を適用した結果をもとに新たな配列を生成するメソッド。関数を引数にするため、高階関数の一つ。

使ってみる

mapメソッドは配列に対して使います。

const changes = [100, 400, -300, 120, -50, -330, 1400, 500];

配列の要素の値を2倍にした新たな配列は次のように定義することができます。

const newChanges = changes.map(function callback(arr) {
  return arr * 2;
});

newChangesの中身をコンソールで確認してみるとそれぞれの要素の値の2倍になっていることが分かります。

console.log(newChanges);
//(8) [200, 800, -600, 240, -100, -660, 2800, 1000]

コールバック関数はアロー関数を使って簡潔に書くことができます。

const newChanges = changes.map(arr => arr * 2);

for of文を使えば同じような結果を得られます。空の配列newChanges2にpushメソッドで2倍にした配列の要素を格納します。

const newChanges2 = [];
for (const change of changes) {
  newChanges2.push(change * 2);
}

console.log(newChanges2);
//(8) [200, 800, -600, 240, -100, -660, 2800, 1000]

mapで使われるcall back関数の引数はvalue, index, arrayの順になります。

const newChanges3 = changes.map((value, i, arr) => {
  return `${i} : ${value * 2} , ${arr}`;
});

console.log(newChanges3);
//(8) ["0 : 200 , 100,400,-300,120,-50,-330,1400,500", "1 : 800 , 100,400,-300,120,-50,-330,1400,500", "2 : -600 , 100,400,-300,120,-50,-330,1400,500", "3 : 240 , 100,400,-300,120,-50,-330,1400,500", "4 : -100 , 100,400,-300,120,-50,-330,1400,500", "5 : -660 , 100,400,-300,120,-50,-330,1400,500", "6 : 2800 , 100,400,-300,120,-50,-330,1400,500", "7 : 1000 , 100,400,-300,120,-50,-330,1400,500"]

参考サイト

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?