迭代对象是 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中文网其他相关文章!