- Learning TypeScript 2.x
- Remo H. Jansen
- 133字
- 2025-04-04 17:02:04
Iterate on each object's properties (for...in)
The for...in statement by itself is not a bad practice; however, it can be misused, for example, to iterate over arrays or array-like objects. The purpose of the for...in statement is to enumerate over object properties:
let obj: any = { a: 1, b: 2, c: 3 }; for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(key + " = " + obj[key]); } } // Output: // "a = 1" // "b = 2" // "c = 3"
The following code snippet will go up in the prototype chain, also enumerating the inherited properties. The for...in statement iterates the entire prototype chain, also enumerating the inherited properties. When you want to enumerate only the object's properties that aren't inherited, you can use the hasOwnProperty method.