Bu örnekte, bir nesnede döngü oluşturacak bir JavaScript programı yazmayı öğreneceksiniz.
Bu örneği anlamak için, aşağıdaki JavaScript programlama konuları hakkında bilgi sahibi olmalısınız:
- JavaScript Nesneleri
- JavaScript için… in döngüsü
Örnek 1: Şunun için Kullanarak Nesnede Döngü
// 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); )
Çıktı
isim - Can yaş - 20 hobi - ("okuma", "oyunlar", "kodlama")
Yukarıdaki örnekte, for… in
döngü student
nesnede döngü yapmak için kullanılır .
Her anahtarın değerine kullanılarak erişilir student(key)
.
Not : for… in
Döngü, miras alınan özellikleri de sayacaktır.
Örneğ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); )
Çıktı
isim - Can'ın yaşı - 20 hobi - ("okuma", "oyunlar", "kodlama") cinsiyet - erkek
İsterseniz, hasOwnProperty()
yöntemi kullanarak yalnızca nesnenin kendi özelliğinde döngü yapabilirsiniz .
if (student.hasOwnProperty(key)) ( ++count: )
Örnek 2: Object.entries ve 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); )
Çıktı
isim - Can yaş - 20 hobi - ("okuma", "oyunlar", "kodlama")
Yukarıdaki programda nesne, Object.entries()
yöntem ve for… of
döngü kullanılarak döngüye alınır.
Object.entries()
Yöntem, belirli bir nesnenin anahtar / değer çiftleri bir dizi döner. for… of
Döngü bir dizi döngü için kullanılır.