zoukankan      html  css  js  c++  java
  • js 遍历对象属性(for in、Object.keys、Object.getOwnProperty) 以及高效地输出 js 数组

    js中几种遍历对象的方法,包括for in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。

    for in

    主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性

    var obj = {"name":"Poly", "career":"it"}
    Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false});
    Object.prototype.protoPer1 = function(){console.log("proto");};
    Object.prototype.protoPer2 = 2;
    console.log("For In : ");
    for(var a in obj) console.log(a);



    Object.keys

    返回一个数组,元素均为对象自有的可枚举属性

    var obj = {"name":"Poly", "career":"it"}
    Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false});
    Object.prototype.protoPer1 = function(){console.log("proto");};
    Object.prototype.protoPer2 = 2;
    console.log("Object.keys:")
    console.log(Object.keys(obj));

     

    Object.getOwnProperty

    用于返回对象的自有属性,包括可枚举和不可枚举的

    var obj = {"name":"Poly", "career":"it"}
    Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false});
    Object.prototype.protoPer1 = function(){console.log("proto");};
    Object.prototype.protoPer2 = 2;
    console.log("Object.getOwnPropertyNames: ");
    console.log(Object.getOwnPropertyNames(obj));

    输出如下:

    怎样快速而优雅地遍历 JavaScript 数组

    // 最快且优雅的代码
    var array = [0,1,2,3,4,5,6,7,8,9];
    
    // while 循环
    var i = array.length;
    while (i–-) {
        fn(array[i]);
    }
  • 相关阅读:
    Luogu 3119 [USACO15JAN]草鉴定Grass Cownoisseur
    Luogu 4514 上帝造题的七分钟
    Luogu 1484 种树
    Luogu【P2904】跨河(DP)
    Luogu【P2065】贪心的果农(DP)
    Luogu【P1725】琪露诺(单调队列,DP)
    二分图匹配
    单调队列
    Tarjan的强联通分量
    手写堆
  • 原文地址:https://www.cnblogs.com/ryanzheng/p/10333905.html
Copyright © 2011-2022 走看看