for in 是 JavaScript 1.0 版本中就有的语法,本文将对 for in 进行详细介绍
1. for in 循环所遍历的范围
for in 循环遍历一个对象的可枚举属性,包括这个对象继承自原型链上的可枚举属性
举个例子:
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
const iterable = [3, 5, 7];
iterable.foo = 'hello';
for (const i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (const i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); // logs 0, 1, 2, "foo"
}
}
让我们一步一步一起解读下以上代码:
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
const iterable = [3, 5, 7];
iterable.foo = 'hello';
每个 Object 对象继承 objCustom 属性;每个 Array 对象继承 arrCustom 属性;声明 iterable 数组(继承 Array 和 Object);又在 iterable 数组中添加 foo 属性
for (const i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
循环遍历可枚举属性 iterable ;3, 5, 7, hello 不能遍历,因为它们不是可枚举属性,实际上也不是对象,它们只是值
for (const i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); // logs 0, 1, 2, "foo"
}
}
通过使用 hasOwnProperty() 对循环遍历的范围进行了一个过滤,只循环对象自身的可枚举属性,不包括 iterable 继承的可枚举属性
以上明白了 for in 所循环遍历的是一个对象的可枚举属性,即对象 数组都可以(数组遍历的是索引)
2. for in 循环中的增删改
在 for in 循环中,增,添加的属性,后面可以被访问,也可以被删除;删,删除之后就不能访问该属性了;改,修改完以后,后面的值就是修改完以后的值了;
即,在 for in 循环中可以进行增删改操作
3. for in 循环体的遍历顺序
for in 是按照可枚举属性进行遍历的,即,是无序的,如果遍历数组,对索引顺序有要求的话,不推荐使用 for in ,推荐使用 for of 、forEach()等其它方法