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

JavaScript におけるオブジェクトの反復を理解する: `for...of` と `for...in`

Sep 26, 2024 pm 03:24 PM

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 までご連絡ください。

ホット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衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptエンジン:実装の比較 JavaScriptエンジン:実装の比較 Apr 13, 2025 am 12:05 AM

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

Python vs. JavaScript:学習曲線と使いやすさ Python vs. JavaScript:学習曲線と使いやすさ Apr 16, 2025 am 12:12 AM

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

C/CからJavaScriptへ:すべてがどのように機能するか C/CからJavaScriptへ:すべてがどのように機能するか Apr 14, 2025 am 12:05 AM

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

JavaScriptとWeb:コア機能とユースケース JavaScriptとWeb:コア機能とユースケース Apr 18, 2025 am 12:19 AM

Web開発におけるJavaScriptの主な用途には、クライアントの相互作用、フォーム検証、非同期通信が含まれます。 1)DOM操作による動的なコンテンツの更新とユーザーインタラクション。 2)ユーザーエクスペリエンスを改善するためにデータを提出する前に、クライアントの検証が実行されます。 3)サーバーとのリフレッシュレス通信は、AJAXテクノロジーを通じて達成されます。

JavaScript in Action:実際の例とプロジェクト JavaScript in Action:実際の例とプロジェクト Apr 19, 2025 am 12:13 AM

現実世界でのJavaScriptのアプリケーションには、フロントエンドとバックエンドの開発が含まれます。 1)DOM操作とイベント処理を含むTODOリストアプリケーションを構築して、フロントエンドアプリケーションを表示します。 2)node.jsを介してRestfulapiを構築し、バックエンドアプリケーションをデモンストレーションします。

JavaScriptエンジンの理解:実装の詳細 JavaScriptエンジンの理解:実装の詳細 Apr 17, 2025 am 12:05 AM

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

Python vs. JavaScript:コミュニティ、ライブラリ、リソース Python vs. JavaScript:コミュニティ、ライブラリ、リソース Apr 15, 2025 am 12:16 AM

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

Python vs. JavaScript:開発環境とツール Python vs. JavaScript:開発環境とツール Apr 26, 2025 am 12:09 AM

開発環境におけるPythonとJavaScriptの両方の選択が重要です。 1)Pythonの開発環境には、Pycharm、Jupyternotebook、Anacondaが含まれます。これらは、データサイエンスと迅速なプロトタイピングに適しています。 2)JavaScriptの開発環境には、フロントエンドおよびバックエンド開発に適したnode.js、vscode、およびwebpackが含まれます。プロジェクトのニーズに応じて適切なツールを選択すると、開発効率とプロジェクトの成功率が向上する可能性があります。

See all articles