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

存在しない要素を取得する

これまでに配列やオブジェクトの扱い方を学習してきました。
では要素を取得する際に、配列に対して存在しないインデックス番号を指定したり、 オブジェクトに対して存在しないプロパティを指定するとどうなるのかを見てみましょう。

image.png

undefined

以下の図のように、配列の存在しないインデックス番号の要素や、オブジェクトの存在しないプロパティの要素を取得しようとすると、undefinedと出力されます。
undefinedは特別な値で、値が定義されていないことを意味します。

image.png

例題

「オブジェクトを要素に持つ配列」ページの2つ目の例題で作成したコードに、要素を追加してみましょう。
定数charactersの配列に、以下のオブジェクトを追加してください。
{ name : "sheep" }

コンソールを実行してみると、undefined歳ですと出力されたかと思います。
このような場合の対処法を、次のundefinedの対応で学習していきましょう。

qiita.js
const characters = [

    { name: "cat", age: 14 },
    
    { name: "turtle", age: 100 },
    
    { name: "dog", age: 5 },
    
    // 要素を追加してください
    
];

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

    console.log("--------------------");

    const character = characters[i];

    console.log(`名前は${character.name}です`);
    
    console.log(`${character.age}歳です`);
}
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?