迭代物件是 JavaScript 中常見的任務,但了解每種情況的正確技術可以使您的程式碼更乾淨、更有效率。本文解釋了為什麼不能直接將 for...of 與物件一起使用,提供了替代方法,並提供了迭代物件的最佳實踐。
在 JavaScript 中,迭代資料結構是處理複雜資料集的重要組成部分。雖然數組和字串是可迭代對象,但普通對象(鍵值對)需要不同的迭代方法。當開發人員嘗試在物件上使用 for...of 時,他們經常會遇到問題。
for...of 迴圈用於迭代可迭代物件,例如陣列、字串、Map 和 Set。然而,預設情況下,普通 JavaScript 物件不可迭代。
const user = { name: 'John', age: 30 }; for (const value of user) { console.log(value); } // TypeError: user is not iterable
嘗試在普通物件上使用 for...of 會引發 TypeError。發生這種情況是因為 JavaScript 中的物件沒有 [Symbol.iterator] 方法,而 for...of 迴圈需要該方法。
要在 JavaScript 迭代對象,可以使用多種技術:
for...in 迴圈迭代物件的可枚舉屬性。它循環遍歷物件的鍵。
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
Object.keys() 傳回物件自身屬性鍵的數組,讓您可以使用 for...of 來迭代它們。
const user = { name: 'John', age: 30 }; for (const key of Object.keys(user)) { console.log(key, user[key]); } // Output: // name John // age 30
Object.values() 傳回物件屬性值的數組,然後可以使用 for...of 進行迭代。
const user = { name: 'John', age: 30 }; for (const value of Object.values(user)) { console.log(value); } // Output: // John // 30
Object.entries() 傳回物件的鍵值對數組,這使得它非常適合迭代鍵和值。
const user = { name: 'John', age: 30 }; for (const [key, value] of Object.entries(user)) { console.log(key, value); } // Output: // name John // age 30
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 |
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.
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
const colors = ['red', 'green', 'blue']; for (const index in colors) { console.log(index, colors[index]); } // Output: // 0 red // 1 green // 2 blue
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.
const colors = ['red', 'green', 'blue']; for (const color of colors) { console.log(color); } // Output: // red // green // blue
const name = 'John'; for (const char of name) { console.log(char); } // Output: // J // o // h // n
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. |
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
以上是理解 JavaScript 中的物件迭代:'for...of”與'for...in”的詳細內容。更多資訊請關注PHP中文網其他相關文章!