for in 与 for of 区别
for in是ES5标准,遍历key.
for of是ES6标准,遍历value.
- 遍历对象:for…in可以,for…of 不可以
- 遍历Map Set: for…of 可以,for…in 不可以
- 遍历 generator:for…of 可以,for…in 不可以
例子
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // 3, 5, 7
}