for in 和 for of 的区别
数据
// 对象数组
let list = [
{num1:12},
{num1:11},
{num2:15}
]
// 普通数组
let arr = [5,3,7]
for of 遍历
- 对象数组使用
for of
for(let i of list){
console.log(i)
}
/** 输出为对象数组的每一个对象
{num1: 12}
{num1: 11}
{num2: 15}
**/
- 普通数组使用
for of
for(let i of arr){
console.log('i : ',i)
}
/** 输出为数组的值
i : 5
i : 3
i : 7
**/
for in
- 对象数组使用
for in
for(let i in arrObj){
console.log(i,arrObj[i])
}
/** 输出为数组的索引index
0 {num1: 12}
1 {num1: 11}
2 {num2: 15}
**/
- 普通数组使用
for in
for(let i in arr){
console.log('i : ',i)
}
/** 输出为数组的索引index
i : 0
i : 1
i : 2
**/
- 对象使用
for in
function Person(){
this.grade = 0;
this.depart = 'xxx';
this.fun = function(){
let a = '1';
}
}
Person.prototype.name = 'x';
Person.prototype.age = 19;
Person.prototype.sex = 'female';
Person.prototype.change = function(){
console.log(this.name);
}
var obj = new Person();
obj.grade = 2017;
for(let key in obj){
if(obj.hasOwnProperty(key)){ // 过滤
console.log(key,obj[key])
}
}
/** 输出为对象的属性
grade 2017
depart xxx
fun ƒ (){ let a = '1';}
**/
/** 注释掉 if(obj.hasOwnProperty(key)) 的输出内容
grade 2017
depart xxx
fun ƒ (){ let a = '1'; }
name x
age 19
sex female
change ƒ (){ console.log(this.name); }
**/
PS:用 obj.hasOwnProperty(key)
是将 实例
的 原型链
上的属性过滤掉,因为在一些对象的原型链上可能会存在许多继承得到的方法和属性,一般是不需要的,因此需要通过这个来过滤掉。
key in obj
会遍历包括原型链上的属性obj.hasOwnProperty(key)
测的是自己本身拥有的属性
总结
for of
遍历的是数组的元素值for of
适用遍历数/数组对象/字符串/map/set等拥有迭代器对象的集合
。但是不能遍历对象,因为没有迭代器对象for in
遍历的是数组的索引for in
是为遍历对象
而设计的,不适用于遍历数组,遍历数组的话效率比for of
低