LoginSignup
62
33

More than 3 years have passed since last update.

JavaScriptの配列(Array)について

Last updated at Posted at 2018-10-13

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つずつ取得できました。

62
33
2

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
62
33