JavaScriptの配列について調べたのでインプットの質を上げるための備忘録として。
配列とは
- 複数の値をもつ構造
- オブジェクト型
今回記述する配列のメソッド
- map
- filter
- forEach
配列のプロパティ
- length
mapメソッド
与えられた関数を配列のすべての要素に対して呼び出し、その結果をまとめた新しい配列として返します 。
const todos = [
{
title: "ご飯を食べる",
where: "レストラン",
},
{
title: "勉強をする",
where:"家",
},
{
title: "寝る",
where: "ベッド",
},
];
const whereTodo = todos.map(x => x.where);
console.log(whereTodo);
出力
["レストラン","家","ベッド"]
それぞれのwhere要素を取り出し新しく配列を作りました。
filterメソッド
全ての配列の要素から関数の条件に一致する配列の要素を見つけ出し、新しい配列を作ります。
const todos = [
{
title: "ご飯を食べる",
where: "レストラン",
},
{
title: "勉強をする",
where:"家",
},
{
title: "寝る",
where: "ベッド",
},
];
const whereTodo = todos.filter(x => x.where === 'ベッド');
console.log(whereTodo);
出力
↓↓↓↓↓↓↓ あなたの記事の内容
[{ title: "寝る", where: "ベッド" }]
───────
[{title: "寝る", where: "ベッド"}]
↑↑↑↑↑↑↑ 編集リクエストの内容
指定した条件に一致する要素を見つけ出し、新しく配列を作りました。
lengthプロパティ
配列の要素数をカウントして出力します。
const todos = [
{
title: "ご飯を食べる",
where: "レストラン",
},
{
title: "勉強をする",
where:"家",
},
{
title: "寝る",
where: "ベッド",
},
];
const whereTodo = todos.length;
console.log(whereTodo);
出力
3
要素数を出力してくれました。
forEach
配列の値1つずつに対してコールバック関数の処理を実行します。
コールバック関数はいくつか引数を受けとることが可能でコールバック関数により、繰り返し処理を実現しています。
mapメソッドとは違い、返り値はありません。
const todos = [
{
title: "ご飯を食べる",
where: "レストラン",
},
{
title: "勉強をする",
where:"家",
},
{
title: "寝る",
where: "ベッド",
},
];
todos.forEach((whereTodo) => {
console.log(whereTodo.where);
});
出力
レストラン
家
ベッド
オブジェクトのwhereを直接指定したので、whereの値が1つずつ取得できました。