検索
ホームページウェブフロントエンドjsチュートリアルJavaScript におけるオブジェクトの反復を理解する: `for...of` と `for...in`

Understanding Object Iteration in JavaScript: `for...of` vs `for...in`

Iterating over objects is a common task in JavaScript, but knowing the correct technique for each situation can make your code cleaner and more efficient. This article explains why you can't use for...of directly with objects, offers alternative approaches, and provides best practices for iterating over objects.

Table of Contents

  1. Introduction to Iteration in JavaScript
  2. Why for...of Doesn’t Work with Objects
  3. Techniques for Iterating Over Objects
    • Using for...in
    • Using Object.keys()
    • Using Object.values()
    • Using Object.entries()
  4. Comparison of Object Iteration Techniques
  5. Comparison Between for...in and for...of
  6. Advanced Example: Iterating Over Nested Objects
  7. Best Practices for Object Iteration in JavaScript

1. Introduction to Iteration in JavaScript

In JavaScript, iterating over data structures is an essential part of handling complex datasets. While arrays and strings are iterable objects, plain objects (key-value pairs) require different methods for iteration. When developers try to use for...of on objects, they often encounter issues.


2. Why for...of Doesn’t Work with Objects

The for...of loop is used to iterate over iterable objects like arrays, strings, Maps, and Sets. Plain JavaScript objects, however, are not iterable by default.

Example: Trying for...of with an Object

const user = { name: 'John', age: 30 };

for (const value of user) {
  console.log(value);
}
// TypeError: user is not iterable

Attempting to use for...of on a plain object throws a TypeError. This happens because objects in JavaScript do not have a [Symbol.iterator] method, which is required for the for...of loop.


3. Techniques for Iterating Over Objects

To iterate over objects in JavaScript, several techniques are available:

3.1 Using for...in

The for...in loop iterates over an object’s enumerable properties. It loops through the keys of the object.

const user = { name: 'John', age: 30 };

for (const key in user) {
  console.log(key, user[key]);
}
// Output: 
// name John
// age 30
  • Pros: Simple and direct.
  • Cons: Iterates over inherited properties if they are enumerable, which might cause unexpected behavior.

3.2 Using Object.keys()

Object.keys() returns an array of the object’s own property keys, allowing you to use for...of to iterate over them.

const user = { name: 'John', age: 30 };

for (const key of Object.keys(user)) {
  console.log(key, user[key]);
}
// Output: 
// name John
// age 30
  • Pros: Only iterates over the object’s own properties.
  • Cons: Only retrieves the keys, not the values.

3.3 Using Object.values()

Object.values() returns an array of the object’s property values, which can then be iterated over with for...of.

const user = { name: 'John', age: 30 };

for (const value of Object.values(user)) {
  console.log(value);
}
// Output: 
// John
// 30
  • Pros: Direct access to values without dealing with keys.
  • Cons: Cannot access the keys directly.

3.4 Using Object.entries()

Object.entries() returns an array of the object’s key-value pairs, which makes it perfect for iterating over both keys and values.

const user = { name: 'John', age: 30 };

for (const [key, value] of Object.entries(user)) {
  console.log(key, value);
}
// Output: 
// name John
// age 30
  • Pros: Easy access to both keys and values in one iteration.
  • Cons: Slightly more complex syntax.

4. Comparison of Object Iteration Techniques

Technique Access to Keys Access to Values Inherited Properties Simplicity
for...in Yes Yes Yes (if enumerable) Simple
Object.keys() for...of Yes No No Moderate
Object.values() for...of No Yes No Moderate
Object.entries() for...of Yes Yes No Slightly complex
Technique
Access to Keys Access to Values Inherited Properties Simplicity
for...in Yes Yes Yes (if enumerable) Simple
Object.keys() for...of Yes No No Moderate
Object.values() for...of No Yes No Moderate
Object.entries() for...of Yes Yes No Slightly complex

5. Comparison Between for...in and for...of

5.1 for...in Loop

The for...in loop is used to iterate over the enumerable properties (keys) of an object, including properties that may be inherited through the prototype chain.

Example: for...in with an Object

const user = { name: 'John', age: 30 };

for (const key in user) {
  console.log(key, user[key]);
}
// Output:
// name John
// age 30
  • Explanation: The for...in loop iterates over the keys (name and age) and allows you to access the corresponding values (John and 30).

Example: for...in with an Array (Not Recommended)

const colors = ['red', 'green', 'blue'];

for (const index in colors) {
  console.log(index, colors[index]);
}
// Output:
// 0 red
// 1 green
// 2 blue
  • Explanation: The for...in loop iterates over the indices (0, 1, 2) of the array, not the values themselves. This behavior is usually less desirable when working with arrays.

5.2 for...of Loop

The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, and other iterables. It loops over the values of the iterable.

Example: for...of with an Array

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color);
}
// Output:
// red
// green
// blue
  • Explanation: The for...of loop directly iterates over the values of the array (red, green, blue), which is ideal for array iteration.

Example: for...of with a String

const name = 'John';

for (const char of name) {
  console.log(char);
}
// Output:
// J
// o
// h
// n
  • Explanation: The for...of loop iterates over each character of the string (J, o, h, n), making it useful for string manipulation.

Summary: Key Differences Between for...in and for...of

Feature for...in for...of
Purpose Iterates over object keys (including inherited properties) Iterates over iterable values (arrays, strings, etc.)
Works with Objects Yes No (objects are not iterable)
Works with Arrays Yes, but not ideal (returns indices) Yes, ideal (returns values)
Use Case Best for iterating over object properties Best for arrays, strings, maps, sets, etc.

6. Advanced Example: Iterating Over Nested Objects

Sometimes, objects are nested, and you need to iterate through all levels of the object. Here's an example that uses recursion to handle nested objects.

const user = {
  name: 'John',
  age: 30,
  address: {
    city: 'New York',
    zip: 10001
  }
};

// Recursively iterate through the object
function iterate(obj) {
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'object' && !Array.isArray(value)) {
      console.log(`Entering nested object: ${key}`);
      iterate(value); // Recursively call for nested objects
    } else {
      console.log(key, value); // Output key-value pair
    }
  }
}

iterate(user);
// Output: 
// name John
// age 30
// Entering nested object: address
// city New York
// zip 10001
  • Explanation: The function checks if the value is an object, then recursively iterates through it.

7. Best Practices for Object Iteration in JavaScript

Use the Right Technique for the Right Task

  1. Use for...in cautiously: It may iterate over properties inherited from the prototype chain,

以上がJavaScript におけるオブジェクトの反復を理解する: `for...of` と `for...in`の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JavaScriptの文字列文字を交換しますJavaScriptの文字列文字を交換しますMar 11, 2025 am 12:07 AM

JavaScript文字列置換法とFAQの詳細な説明 この記事では、javaScriptの文字列文字を置き換える2つの方法について説明します:内部JavaScriptコードとWebページの内部HTML。 JavaScriptコード内の文字列を交換します 最も直接的な方法は、置換()メソッドを使用することです。 str = str.replace( "find"、 "置換"); この方法は、最初の一致のみを置き換えます。すべての一致を置き換えるには、正規表現を使用して、グローバルフラグGを追加します。 str = str.replace(/fi

カスタムGoogle検索APIセットアップチュートリアルカスタムGoogle検索APIセットアップチュートリアルMar 04, 2025 am 01:06 AM

このチュートリアルでは、カスタムGoogle検索APIをブログまたはWebサイトに統合する方法を示し、標準のWordPressテーマ検索関数よりも洗練された検索エクスペリエンスを提供します。 驚くほど簡単です!検索をyに制限することができます

例JSONファイルの例例JSONファイルの例Mar 03, 2025 am 12:35 AM

この記事シリーズは、2017年半ばに最新の情報と新鮮な例で書き直されました。 このJSONの例では、JSON形式を使用してファイルに単純な値を保存する方法について説明します。 キー価値ペア表記を使用して、あらゆる種類を保存できます

10 jQuery構文蛍光物10 jQuery構文蛍光物Mar 02, 2025 am 12:32 AM

コードプレゼンテーションを強化する:開発者向けの10個の構文蛍光物 ウェブサイトやブログでコードスニペットを共有することは、開発者にとって一般的な慣行です。 適切な構文ハイライターを選択すると、読みやすさと視覚的な魅力を大幅に改善できます。 t

独自のAjax Webアプリケーションを構築します独自のAjax Webアプリケーションを構築しますMar 09, 2025 am 12:11 AM

それで、あなたはここで、Ajaxと呼ばれるこのことについてすべてを学ぶ準備ができています。しかし、それは正確には何ですか? Ajaxという用語は、動的でインタラクティブなWebコンテンツを作成するために使用されるテクノロジーのゆるいグループ化を指します。 Ajaxという用語は、もともとJesse Jによって造られました

8見事なjQueryページレイアウトプラグイン8見事なjQueryページレイアウトプラグインMar 06, 2025 am 12:48 AM

楽なWebページレイアウトのためにjQueryを活用する:8本質的なプラグイン jQueryは、Webページのレイアウトを大幅に簡素化します。 この記事では、プロセスを合理化する8つの強力なjQueryプラグイン、特に手動のウェブサイトの作成に役立ちます

10 JavaScript&JQuery MVCチュートリアル10 JavaScript&JQuery MVCチュートリアルMar 02, 2025 am 01:16 AM

この記事では、JavaScriptとJQuery Model-View-Controller(MVC)フレームワークに関する10を超えるチュートリアルの厳選された選択を紹介します。これは、新年にWeb開発スキルを向上させるのに最適です。 これらのチュートリアルは、Foundatioのさまざまなトピックをカバーしています

' this' JavaScriptで?' this' JavaScriptで?Mar 04, 2025 am 01:15 AM

コアポイント これは通常、メソッドを「所有」するオブジェクトを指しますが、関数がどのように呼び出されるかに依存します。 現在のオブジェクトがない場合、これはグローバルオブジェクトを指します。 Webブラウザでは、ウィンドウで表されます。 関数を呼び出すと、これはグローバルオブジェクトを維持しますが、オブジェクトコンストラクターまたはそのメソッドを呼び出すとき、これはオブジェクトのインスタンスを指します。 call()、apply()、bind()などのメソッドを使用して、このコンテキストを変更できます。これらのメソッドは、与えられたこの値とパラメーターを使用して関数を呼び出します。 JavaScriptは優れたプログラミング言語です。数年前、この文はそうでした

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。