for-of是ES6引进的新语法,for-in循环是遍历对象的属性,for-of循环是遍历实现iterator接口的成员
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}
通过上面的例子可以看出,for-of会忽略不可迭代的属性
本文详细解析了ES6中for-of与for-in循环的区别与应用场景。for-in循环用于遍历对象属性,而for-of循环则专门用于遍历可迭代对象,如数组。文章通过实例展示了两种循环的不同行为,强调了for-of循环对于忽略非迭代属性的优势。
535

被折叠的 条评论
为什么被折叠?



