javascript中对象的assign()方法

您所在的位置:网站首页 js对象方法的使用 javascript中对象的assign()方法

javascript中对象的assign()方法

2024-07-15 05:01| 来源: 网络整理| 查看: 265

javascript中对象的assign()方法

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

语法:

Object.assign(target,...sources)

参数:

target:新对象,用来接受的对象

sources:源对象。

返回值:

目标对象,新对象。

示例:

1.用来把几个对象合并到一个对象

let json1 = {a:1} let json2 = {b:2} let json3 = {c:3} let json =Object.assign ({},json1,json2,json3); console.log(json); // {a: 1, b: 2, c: 3}

1.1 后面的sources里面的属性会覆盖前面的属性

let json1 = {a:1} let json2 = {b:2,a:2} let json3 = {c:3} let json =Object.assign ({},json1,json2,json3); console.log(json); // {a: 2, b: 2, c: 3}

2. 可以浅复制一个对象

let json = { a:"a", b:"b", c:"c" } let json2 = Object.assign({},json) json2.b = "d"; console.log(json2); //{a: "a", b: "d", c: "c"} console.log(json); //{a: "a", b: "b", c: "c"}

 

如果需要深拷贝的话,请去mdn自行查看



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3