1. for...in 循環
(1). 格式:
- for (const propertyName in object) { //statement; };
如:let animal = {
name: 'duck',
age: 3
};
for (let prop in animal) {
console.log(prop + ' : ' + animal[prop]);
}; // name: cat age: 3
(2). for...in 循環既會遍歷本對象的屬性,同時也會遍歷已繼承的父對象的屬性。
如:let animals = {mammals:‘carnivora’};
let cat = Object.create(animals);
cat.name = 'cat';
for (const prop in cat){
console.log(prop);
}; // name mammals
- 如果不想同時遍歷父對象的屬性,可以使用hasOwnProperty()方法。
如:for (const prop in cat){
if (cat.hasOwnProperty(prop))
console.log(prop);
}; // name
(3). for..in 循環在數組中的應用
注意事項:
- 遍歷順序有可能不是按照實際數組的内部順序。所以,如果對遍歷結果的順序有要求的話,不要使用for..in循環。
- 索引(即,key)為字符串型的數字,并不能直接進行幾何運算。