1. 程式人生 > >for in,Object.keys()與for of的區別

for in,Object.keys()與for of的區別

-o https map對象 tps 屬性 get for his ron

for in

  • for in一般用於遍歷對象的屬性;
  • 作用於數組的for in除了會遍歷數組元素外,還會遍歷自定義可枚舉的屬性,以及原型鏈上可枚舉的屬性;
  • 作用於數組的for in的遍歷結果是數組的索引,且都為字符串型,不能用於運算;
  • 某些情況下,可能按照隨機順序遍歷數組元素;
 1  Array.prototype.sayLength = function(){
 2    console.log(this.length);
 3    }
 4  let arr = [‘a‘,‘b‘,‘c‘,‘d‘];
 5  arr.name = ‘數組‘;
 6  Object.defineProperties(arr,{
7 type:{ 8 value:true, 9 writable:true, 10 enumerable:true 11 } 12 }); 13 for(let i in arr){ 14 console.log(i);//0,1,2,3,name,type,sayLength 15 }


Object.keys()

  • 遍歷結果為由對象自身可枚舉屬性組成的數組,數組中的屬性名排列順序與使用for in循環遍歷該對象時返回的順序一致;
  • 與for in區別在於不能遍歷出原型鏈上的屬性;
 Array.prototype.sayLength = function(){
            console.log(this.length);
        }
        let arr = [‘a‘,‘b‘,‘c‘,‘d‘];
        arr.name = ‘數組‘;
        Object.defineProperties(arr,{
            type:{
                value:true,
                writable:true,
                enumerable:
true } }); var keys = Object.keys(arr); console.log(keys);//["0", "1", "2", "3", "name", "type"]


for of

  • ES6中添加的循環語法;
  • for of支持遍歷數組、類對象(例如DOM NodeList對象)、字符串、Map對象、Set對象;
  • for of不支持遍歷普通對象,可通過與Object.keys()搭配使用遍歷;(見示例二)
  • for of遍歷後的輸出結果為數組元素的值;

示例一:

 1 Array.prototype.sayLength = function(){
 2  console.log(this.length);
 3}
 4  let arr = [‘a‘,‘b‘,‘c‘,‘d‘];
 5  arr.name = ‘數組‘;
 6  Object.defineProperties(arr,{
 7  type:{
 8        value:true,
 9        writable:true,
10        enumerable:true
11       }
12 });
13  for(let i of arr){
14      console.log(i);//a,b,c,d
15  }

示例二:

var person={
    name:‘coco‘,
    age:22,
    locate:{
        country:‘China‘,
        city:‘beijing‘,
    }
}
for(var key of Object.keys(person)){
    //使用Object.keys()方法獲取對象key的數組
    console.log(key+": "+person[key]);//name: coco,age: 22,locate: [object Object]
}

PS:讓jquery對象支持for of遍歷

// 因為jQuery對象與數組相似
// 可以為其添加與數組一致的叠代器方法

jQuery.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

註:本文部分內容來自以下鏈接內容

MDN web docs

深入淺出ES6(二)

杜培東的博客

for in,Object.keys()與for of的區別