1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】find()クイズ!

Last updated at Posted at 2021-10-08

棚に以下が置いてあります。

const stack = [
   {name:"たまねぎ", date:true}, 
   {name:"葡萄", date:false}, 
   {name:"たまねぎ", date:false}, 
   {name:"林檎", date:false},
];

今日はカレーを作りたいので「たまねぎ」が欲しいです。
以下のように欲しい食材を定義しました。

const target = {name:"たまねぎ"};

では、findを用いて「たまねぎ」を棚から取りましょう。注意点としてdate(消費期限)が切れる前の「たまねぎ」だけを棚から取りましょう。
※trueは賞味期限が切れていません。

答え

const TAMANEGI = stack.find((food)=>{
  if(!food.date){
    return false
  }
  return food.name === target.name;
})

さらにレベルアップ

条件に合う「たまねぎ」がない場合は「undifinde」が返りますが、そんなもの食べられないので、食べ物を返しましょう。以下のコードの一部を書き換えconsole.logで「いただきます!」を出力してください。

  const stack = [
    { name: "たまねぎ", date: true },
    { name: "葡萄", date: false },
    { name: "たまねぎ", date: false },
    { name: "林檎", date: false }
  ];

  const target = { name: "たまねぎマン" };

  const TAMANEGI = stack.find((food) => {
    if (!food.date) {
      return false;
    }
    return food.name === target.name;
  });

  if ("らーめん" === TAMANEGI.name) {
    console.log("いただきます!");
  }

答え

  const stack = [
    { name: "たまねぎ", date: true },
    { name: "葡萄", date: false },
    { name: "たまねぎ", date: false },
    { name: "林檎", date: false }
  ];

  const target = { name: "たまねぎマン" };

  const TAMANEGI = stack.find((food) => {
    if (!food.date) {
      return false;
    }
    return food.name === target.name;
  }) ?? { name: "らーめん" };

  if ("らーめん" === TAMANEGI.name) {
    console.log("いただきます!");
  }

null合体演算子最強!!

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?