不说废话,直接上干货
1. for of 用于遍历可迭代对象(如自定义可迭代对象、数组、字符串也包括其它伪数组等等)。那什么是可迭代对象?es6规定,一个对象如果具有知名符号属性symbol.iterator并且属性值是一个迭代器函数,则该对象是可迭代的即可使用for of。对迭代器和可迭代对象感兴趣的可参考链接。
用法:
const obj = {
a: 1,
b: 2,
[Symbol.iterator]() {
var arr = Object.keys(this);
let index = 0;
return {
next: () => {
const obj = {
key: arr[index],
value: this[arr[index]], //for of 只会返回value
done: arr.length > index ? false : true,
};
index++;
return obj;
},
};
},
};
//遍历自定义可迭代对象
for (const item of obj) {
console.log(item); //1,2
}
//字符串属于伪数组也是标准的可迭代对象
const str = 'abc';
for(const item of str){
console.log(item) //'a', 'b', 'c'
}
2.for in用于遍历普通对象(数组也是对象的一种)。
用法
const obj = {
a:1,
b:2
}
for(prop in obj){
console.log(prop); //'a','b'
}
注意点:for in循环可以遍历对象从原型链上继承的属性,但是不可遍历symbol属性。这里有 些小伙伴就会发出疑问了。为什么一个对象原型链上有那么多方法和属性怎么没看到被遍历出来呢?难道是有什么魔法?Object.getOwnPropertyDescriptors(对象)这个函数就可以解开问题。可以得到一个对象每个属性的属性描述符