• for in,Object.keys()与for of的用法与区别


    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
    }
    })
    // for in 一般用于遍历对象的属性;
    1.作用于数组的for in除了会遍历数组元素外,还会遍历自定义可枚举的属性,以及原型链上可枚举的属性;
    2.作用于数组的for in的遍历结果是数组的索引,且都为字符串型,不能用于运算;
    3.某些情况下,可能按照随机顺序遍历数组元素;
    for(let i in arr){ //输出的都是属性
    console.log(i) //0,1,2,3,name,type,sayLength
    }

    Object.keys()
    1.遍历结果为对象自身可枚举属性组成的数组,数组中的属性名排列顺序与使用for in循环遍历该对象时返回的顺序一致,
    2.与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
    1.es6中添加的循环语法;
    // 2.for of支持遍历数组、类对象(例如:DOM NodeList)、字符串、map对象、Set对象
    3.for of不支持遍历普通对象,可通过与Object.keys()搭配使用遍历(例子2);
    4.for of 遍历后的输出结果为数组元素的值;
    5搭配实例方法entries(),同时输出数组内容弄和索引(例子2)
    例子1


    * */
    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
    }
    });

    for(let i of arr){
    console.log(i);// a,b,c,d
    }

    //例子2

    var person={
    name:'coco',
    age:24,
    locate:{
    country:'china',
    city:'beijing',
    }
    }

    for(var key of Object.keys(person)){
    //使用Object.keys()方法获取对象key的数组
    console.log(key+":"+person[key]);//name:coco age:24 locate:[object Object]

    }

    //例子3
    let arr3=['a','b','c'];
    for(let [index,val] of arr3.entries()){
    console.log(index+":"+val);
    }


    //让jquery对象支持for of遍历
    // 因为jQuery对象与数组相似
    // 可以为其添加与数组一致的迭代器方法

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

  • 相关阅读:
    linux rar安装
    ce
    Hp培训学习注册攻略
    Novell云计算
    bigdata
    Quest *nix Xwindows
    Foglight 5.6.7 控制台jboss报404
    view
    架构-数据库访问-SQL语言进行连接数据库服务器-DB-Library:DB-Library
    架构-数据库访问-SQL语言进行连接数据库服务器:SQL语言进行连接数据库服务器
  • 原文地址:https://www.cnblogs.com/h5it/p/9700827.html
Copyright © 2020-2023  润新知