オブジェクトをループするJavaScriptプログラム

Javascript

例1:for … inを使用してオブジェクトをループする

// program to loop through an object using for...in loop

const student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

// using for...in
for (let key in student) { 
    let value;

    // get the value
    value = student[key];

    console.log(key + " - " +  value); 
} 

出力

name - John
age - 20
hobbies - ["reading", "games", "coding"]

上記の例では、 for...in ループはループスルーに使用されます student オブジェクト。

各キーの値は、を使用してアクセスされます student[key]

注意for...in ループは継承されたプロパティもカウントします。

例えば、

const student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

const person = {
    gender: 'male'
}

// inheriting property
student.__proto__ = person;

for (let key in student) { 
    let value;

    // get the value
    value = student[key];

    console.log(key + " - " +  value);
} 

出力

name - John
age - 20
hobbies - ["reading", "games", "coding"]
gender - male

必要に応じて、オブジェクト自体のプロパティをループできるのは、 hasOwnProperty() 方法。

if (student.hasOwnProperty(key)) {
    ++count:
}

例2:Object.entriesとfor … ofを使用してオブジェクトをループする

// program to loop through an object using for...in loop

const student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

// using Object.entries
// using for...of loop
for (let [key, value] of Object.entries(student)) {
    console.log(key + " - " +  value);
}

出力

name - John
age - 20
hobbies - ["reading", "games", "coding"]

上記のプログラムでは、オブジェクトはを使用してループされます Object.entries() メソッドと for...of ループ。

ザ・ Object.entries() メソッドは、指定されたオブジェクトのキーと値のペアの配列を返します。 ザ・ for...of loopは、配列をループするために使用されます。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です