1. 程式人生 > >javascript中物件的assign()方法

javascript中物件的assign()方法

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自行檢視