for in和for of的区别

for in遍历的是数组的索引
for of遍历的是数组的元素值

  1. for in 中 index索引为字符串型数字,不能直接进行几何运算
for(var index in [1,2,3]){
    console.log(typeof index)//string
}

  1. for in 遍历顺序有可能不是按照实际数组的内部顺序
    因为for in是遍历可枚举的属性,也包括原型上的属性
    遍历数组(不推荐用来遍历数组)
Array.prototype.getName=function(){
return this.name;
}
var arr=[1,2,3];
arr.name="array";
for(var index in arr){
console.log(arr[index]);//1 2 3 array ƒ (){console.log(this.length);}  ƒ (){return this.name;}
}

遍历对象

Object.prototype.getName=function(){
return this.name;
}
var obj={
a:1,
b:2,
c:3
}

for(var index in obj){
console.log(obj[index]);//1 2 3 function(){return this.name;}
}

如果不想遍历原型上的属性,可以通过hasOwnProperty来判断某个属性是属于原型还是实例上

Object.prototype.getName=function(){
return this.name;
}
var obj={
a:1,
b:2,
c:3
}

for(var index in obj){
if(obj.hasOwnProperty(index)){
console.log(obj[index]);//1 2 3
}
}
  1. 而for of 只是遍历数组的内部,不会遍历原型上的属性和索引
Array.prototype.getName=function(){
return this.name;
}
var arr=[1,2,3];
arr.name="array";
for(var item of arr){
console.log(item);//1 2 3
}

也可以通过ES5的Object.keys(obj)来获取实例对象上的属性组成的数组

Object.keys(obj)   //["a", "b", "c"]
  1. 一般是使用for in 来遍历对象,for of 遍历数组

参考文章:call和apply的区别

你可能感兴趣的:(for in和for of的区别)