Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Iterating Over Object Properties with the for...in Loop | Section
JavaScript Data Structures

bookIterating Over Object Properties with the for...in Loop

メニューを表示するにはスワイプしてください

In this section, we will explore advanced concepts of working with objects. Specifically, we will cover iteration through objects and helpful methods JavaScript offers to work with objects effectively. Let's get started.

for...in loop

To work with the properties of an object, including iterating through them, we can use the for...in loop. This loop allows us to traverse an object and access its properties and their values.

The for...in loop is a construct in JavaScript designed specifically for iterating over the properties of an object. It provides a way to access each property's name (key) and its corresponding value.

Here's the basic syntax of the for...in loop:

for (let key in object) {
  // Code to be executed for each property
}
  • key: A variable that will hold the name of the current property during each iteration;
  • object: The object we want to iterate through.

Iterating Through Object Properties in Practice

Let's consider an example with an object representing a flower:

const flower = {
  genus: "Allium",
  species: "Allium sativum",
  color: "Purple",
  height: 24,
  isEdible: true,
  isBlooming: true,
};

Now, let's use the for...in loop to iterate through the properties of the flower object and log each property name and its value:

123456789101112
const flower = { genus: "Allium", species: "Allium sativum", color: "Purple", height: 24, isEdible: true, isBlooming: true, }; for (let key in flower) { console.log(`Property: ${key}, Value: ${flower[key]}`); }
copy

1. What is the primary purpose of the for...in loop when working with objects?

2. What does the key variable represent in the for...in loop?

3. Which part of the for...in loop syntax contains the object you want to iterate through?

4. What will be logged when iterating through the motorbike object's properties in the code below?

question mark

What is the primary purpose of the for...in loop when working with objects?

正しい答えを選んでください

question mark

What does the key variable represent in the for...in loop?

正しい答えを選んでください

question mark

Which part of the for...in loop syntax contains the object you want to iterate through?

正しい答えを選んでください

question mark

What will be logged when iterating through the motorbike object's properties in the code below?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  13

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  13
some-alt