bigname


汇总遍历对象的六种方式及其区别


遍历对象属性方式千千万,奈何网上资料乱又乱!

前言:
本来计划写一篇关于深浅克隆的文章,奈何对各种遍历对象的方式搞得一头雾水,分不清各家的关系。所以特来先汇总一下。

本文汇总了遍历对象的各种方式以及各种方式的差异性,收藏好。以后遇到深浅克隆等功能时说不定能用上。还请客官点个赞再走。

先定义数据源

下面打印的结果都是基于该数据源进行


    let person = {
        name: \'tony\',
    }
    let human = {
        eat: \'food\',
    }

    // human增加属性: symbol
    let width = Symbol();
    human[width] = 177;
    
    // 设置prototype为human
    Object.setPrototypeOf(person, human);
    
    // person增加属性:不可枚举 age
    Object.defineProperty(person, "age", {
        value: "12",
        enumerable: false
    });
    
    // person增加属性:symbol height
    let height = Symbol();
    person[height] = 177;

@

一:for...in...

  • 遍历自身属性
  • 遍历原型链属性
  • 遍历可枚举属性
  • 不遍历symbol
    // 方式一: for in
    console.log(\'----for...in-----\')
    for(let key in person) {
        console.log(key);
    }

打印结果:
name、eat

二:Object.keys

  • 遍历自身属性
  • 不遍历原型链属性
  • 遍历可枚举属性
  • 不遍历symbol
// 方式二:Object.keys
    console.log(\'-----Object.keys-------\')
    let keys = Object.keys(person);
    for(let i = 0; i < keys.length; i++) {
        console.log(person[keys[i]]);
    }

打印结果:
name

三:Object.getOwnPropertyNames

  • 遍历自身属性
  • 不遍历原型链属性
  • 遍历可枚举属性+不可枚举属性
  • 不遍历symbol
    // 方式三:Object.keys
    console.log(\'-----Object.getOwnPropertyNames-------\')
    let ownPropertyNames = Object.getOwnPropertyNames(person);
    for(let i = 0; i < ownPropertyNames.length; i++) {
        console.log(ownPropertyNames[i]);
    }

打印结果:
name 、 age

四:Object.getOwnPropertySymbols

  • 遍历自身的symbol
    // 方式三:Object.keys
    console.log(\'-----Object.getOwnPropertySymbols-------\')
    let ownPropertySymbols = Object.getOwnPropertySymbols(person);
    for(let i = 0; i < ownPropertySymbols.length; i++) {
        console.log(ownPropertySymbols[i]);
    }

打印结果:Symbol

五:Reflect.ownKeys

  • 遍历自身属性
  • 不遍历原型链属性
  • 遍历可枚举属性+不可枚举属性
  • 遍历symbol
   // 方式五:Reflect.ownKeys
    console.log(\'-----Reflect.ownKeys-------\')
    let ownKeys = Reflect.ownKeys(person);
    for(let i = 0; i < ownKeys.length; i++) {
        console.log(ownKeys[i]);
    }

打印结果:
name, age, symbol

六:Object.entries

  • 遍历自身属性
  • 不遍历原型链属性
  • 遍历可枚举属性
  • 不遍历symbol
  • 返回键值对数组(可搭配数组结构赋值使用)
    // 方式六:Object.entries
    console.log(\'-----Object.entries-------\')
    let entries = Object.entries(person);
    for (const [key, value] of entries) {
        console.log(`${key}: ${value}`);
    }

打印结果:
name: tony

总结:

在这里插入图片描述

分类:

技术点:

相关文章: