Linux 拨号vps windows公众号手机端

es6合并对象的方法是什么

lewis 8年前 (2017-06-14) 阅读数 8 #程序编程
文章标签 es6

ES6合并对象的方法有以下几种:

  1. 使用对象展开运算符(…):

    const obj1 = {a: 1, b: 2};
    const obj2 = {c: 3, d: 4};
    const merged = {...obj1, ...obj2};
    console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
    
  2. 使用Object.assign()方法:

    const obj1 = {a: 1, b: 2};
    const obj2 = {c: 3, d: 4};
    const merged = Object.assign({}, obj1, obj2);
    console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
    
  3. 使用Object.getOwnPropertyDescriptors()方法和Object.defineProperties()方法:

    const obj1 = {a: 1, b: 2};
    const obj2 = {c: 3, d: 4};
    const descriptors = Object.getOwnPropertyDescriptors(obj2);
    const merged = Object.defineProperties(obj1, descriptors);
    console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
    

这些方法都可以用来合并多个对象的属性,并创建一个新的对象。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门