JavaScript配列map()
例
すべての要素値の平方根を持つ新しい配列を返します。
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
配列内のすべての値に10を掛けます。
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
以下のその他の例。
定義と使用法
map()
すべての配列要素に対して関数を呼び出して、新しい配列を作成します。
map()
配列内の要素ごとに1回関数を呼び出します。
map()
空の要素に対して関数を実行しません。
map()
元の配列は変更されません。
構文
array.map(function(currentValue, index, arr), thisValue)
パラメーター
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default value undefined .A value passed to the function to be used as its this value. |
戻り値
タイプ | 説明 |
配列 | 各配列要素の関数の結果。 |
ブラウザのサポート
map()
ECMAScript5(ES5)機能です。
ES5(JavaScript 2009)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
その他の例
各人のフルネームを取得します。
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}