含义
两者都是用来遍历。for in遍历的是对象的索引,即key,for of遍历的是对象的值。但对于普通的没有部署iterator的对象,使用for of会报错
for in的特点
- for in遍历的是对象的 键名
- 遍历对象时返回的对象的key值,遍历数组时返回的下标
- for in不仅会遍历数字键名,还会遍历手动添加的属性,如下
- 非排序属性按声明的先后顺序返回key
- key 值的类型都为字符串
- 会遍历原型上的内容
const arr = [1, 2, 3, 4];
arr.name = 'arr';
arr.text = 'test';
for(let key in arr) {
console.log(key);
}
// 输出:0, 1, 2, 3, name, text
// 若打印 typeof key 将得到结果 string
for of特点
- 获取键值对中的值
- 只能遍历部署了Symbol.iterator属性的对象
- for of 和 forEach不同在于,for of可以搭配 continue、break、return使用,可以随时停止遍历
具有Symbol.iterator属性的对象:数组、map、set、string、arguments对象、NodeList(虚拟dom列表)
练习
常规输出
const arr = [null, undefiend, 1, 2, 3];
arr.text = 'test'
for(let key in arr) {
console.log(key);
}
// 输出:0, 1, 2, 3, 4, text
for(let value of arr) {
console.log(value);
}
// 输出:null, undefined, 1, 2, 3
特殊数组
const arr = [];
arr[9] = 10;
arr[10] = 11;
for(const index in arr) {
console.log(index);
}
//输出 8 9
for(const value of arr) {
console.log(value);
}
// 输出:9个undefined 9 10