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

undefinedの対応

Last updated at Posted at 2025-03-15

undefinedを避ける

下の図のように値が存在しない時にundefined歳ですと出力されてしまいます。
代わりに年齢は秘密ですと出力する方法を学んでみましょう。

image.png

undefinedとif文

undefinedif文の条件式に使ってみましょう。
character.ageの値がundefinedと等しいかどうかで処理を分岐します。

image.png

例題

for文内でcharacter.ageに応じてif文で処理を分岐し、undefinedなら「年齢は秘密です」、そうでなければ〇〇歳ですと出力してみましょう。 〇〇の部分はcharacter.ageの値とします。

qiita.js
const characters = [

  {name: "cat", age: 14},
  
  {name: "turtle", age: 100},
  
  {name: "dog", age: 5},
  
  {name: "sheep"}
  
];

for (let i = 0; i < characters.length; i++) {

  console.log("--------------------");
  
  const character = characters[i];
  
  console.log(`名前は${character.name}です`);

  // if文を追加してくださいconsole.log(animals[i]);
  
}
0
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
0
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?