zoukankan      html  css  js  c++  java
  • for in,Object.keys()与for of的区别

    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遍历后的输出结果为数组元素的值;
    • 搭配实例方法entries(),同时输出数组内容和索引;(见示例三)

    示例一:

     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]
    }

    示例三:

    1 let arr3 = ['a', 'b', 'c'];
    2         for (let [index, val] of arr3.entries()) {
    3             console.log(index + ':' + val);//0:a 1:b 2:c
    4         }

    PS:让jquery对象支持for of遍历

    // 因为jQuery对象与数组相似
    // 可以为其添加与数组一致的迭代器方法
    
    jQuery.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    

     

    注:本文部分内容来自以下链接内容

    MDN web docs

    深入浅出ES6(二)

    杜培东的博客

     

  • 相关阅读:
    url参数的获取
    ajax变量作用域的问题
    滚动条自适应宽度的问题
    js发送验证码(倒计时)
    字符串
    值类型和引用类型
    面向对象
    进程
    UI事件
    鼠标跟随
  • 原文地址:https://www.cnblogs.com/nerrol/p/8137065.html
Copyright © 2011-2022 走看看