LoginSignup
0
0

More than 1 year has passed since last update.

お母さんでもわかるJavaScript「オブジェクト、map、filter」

Last updated at Posted at 2023-03-23

オブジェクトの省略

index.js
const name = "清水";
const age = 24;

const user = {
    name:name,
    age:age,
};

//下記のように省略できる
const user{
    name,
    age,
};

mapについて

関数内に実行したい処理を書いておくことで、配列の各要素に対して好きな操作をし、その結果を新しい配列として返すことが出来る。

index.js
const arr2 = ["1です", "2です", "3です"];

//引数に配列の値が設定されます
const arr4 = arr2.map((arr) => {
  console.log(arr);//1です 2です 3です
});


const arr4 = arr2.map((arr) => {
  return arr;
});
console.log(arr4);//['1です', '2です', '3です']


//if文も使えるよ
const name = ["清水", "伊藤", "金子"];
const newNum = name.map((name) => {
  if (name === "清水") {
    return name;
  } else {
    return `${name}さん`;
  }
});
console.log(newNum);//['清水', '伊藤さん', '金子さん']

上記の結果を見るに、arr自体はただのループ処理で、returnで返したarr4は新しい配列になる。

filter

使い方はmapと変わりないが、条件に合う値のみを返却することができる。

index.js
const num = [1, 2, 3, 4, 5, 6];
const oddNum = num.filter((num) => {
  return num % 2 === 1;
});
console.log(oddNum);//[1,3,5]
0
0
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
0
0