protypeMethodのmap()とforEachの違い
Array.prototype.map() とは
map()
メゾットは、与えられた関数を配列のすべての要素に対して呼び出し、
その結果からなる新しい配列を生成する。
example.jsconst array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); return console.log(map1);
結果
example.js> Array [2, 8, 18, 32]
Array.prototype.forEach() とは
forEach()
メソッドは与えられた関数を、配列の各要素に対して一度ずつ実行する。
example.jsconst array1 = ['a', 'b', 'c']; return array1.forEach(x => console.log(x));
結果
example.js> "a" > "b" > "c"
つまり、map()とforEach()の違いは?
- map()はmap()内の作業を各要素ごとに実行し新しい配列を生成すること。
- forEach()はforEach()内の=>以降の作業を要素分、一行ずつ実行される。