let person = { firstName: 'John', lastName: 'Doe', ssn: '299-24-2351', } for (const prop in person) { console.log(prop + ':' + person[prop]) } firstName: John lastName: Doe ssn: 299 - 24 - 2351
The for...in loop & Inheritance
When you loop over the properties of an object that inherits from another object, the for...in statement goes up in the prototype chain and enumerates inherited properties.
1 2 3 4 5 6 7 8 9 10
var decoration = { color: 'red', } var circle = Object.create(decoration) circle.radius = 10 for (const prop in circle) { console.log(prop) } radius color
The circle object has its own prototype that references the decoration object. Therefore, the for...in loop displays the properties of the circle object and its prototype.
如果只想枚举对象自己的属性,可以使用 hasOwnProperty() 方法:
1 2 3 4 5 6
for (const prop in circle) { if (circle.hasOwnProperty(prop)) { console.log(prop) } } radius
The for…in loop and Array
最好不要使用 for…in 来迭代数组,特别是当数组元素的顺序很重要时。
下面的例子可以完美地工作:
1 2 3 4 5 6
const items = [10, 20, 30] let total = 0 for (const item in items) { total += items[item] } console.log(total) // 60
var arr = [] // set the third element to 3, other elements are `undefined` arr[2] = 3 for (let i = 0; i < arr.length; i++) { console.log(arr[i]) } // 输出显示了数组的三个元素,这是正确的: undefined undefined 3
但是,for…in 循环忽略前两个元素:
1 2 3 4
for (const key in arr) { console.log(arr[key]) } // 3