let list = [2, 3, 4];
list.a = "a"
for (let item of list) {
//for of只可以循环可迭代对象的可迭代属性,不可迭代属性在循环中被忽略了。
console.log(item) // 2,3,4 遍历可迭代属性值
}
console.log("---------我是分割线---------")
for (let item in list) {
console.log(item) // 0,1,2,a 作用于数组的for in不仅遍历数组元素,还遍历数组自定义属性,遍历可枚举属性
}
console.log("---------我是分割线---------")
let obj = { "property1": "property1", "property2": "property2" }
for (let item in obj) {
console.log(item) //property1,property2
}
console.log("---------我是分割线---------")
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"
}
console.log("---------我是分割线---------")
for (let i of iterable) {
console.log(i); // 3, 5, 7
}
console.log("---------我是分割线---------")
for (let item of obj) {
console.log(item) // Uncaught TypeError: obj is not iterable
}
console