传播运算符简单示例

Spread Operator simple examples

复制可以通过3种方式实现:

  1. Object.assign
  2. Lodash 库
  3. 同时用于 'Spread (operator)' 和 'Rest (parameter)'

我需要 'Spread (operator)' 和 'Rest (parameter)'

的简单用法示例

'Spread (operator)' 和 'Rest (parameter)'

的简单用法示例
var a = {b: 'b', c: ['c1', 'c2'], d: {d1: 'd1', d2: 'd2'}}
    a.log -> {b: "b", c: ["c1", "c2"], d: {d1: "d1", d2: "d2"}}
    //////////////////////////////////////////////////////////////////////////////
    // Copy a and update c to empty array
    var a1 = {...a, c: []}
    a1.log -> {b: "b", c: [], d: {d1: "d1", d2: "d2"}}
    
    a.d === a1.d   // same object
    true
//////////////////////////////////////////////////////////////////////////////
    // Copy a and copy c 
    var a1 = {...a, c: [...a.c]}
    a1.log -> {b: "b", c: ["c1", "c2"], d: {d1: "d1", d2: "d2"}}
    a.c === a1.c    // different object
    false
    a.d === a1.d   // same object
    true
    
    //////////////////////////////////////////////////////////////////////////////
    // Copy a and copy c. Remove element 'c1' add element 'c4'
    var a1 = {...a, c: [...a.c.filter(e => e !== 'c1'), 'c4']}
    a1.log -> {b: "b", c: ["c2", "c4"], d: {d1: "d1", d2: "d2"}}
    
    //////////////////////////////////////////////////////////////////////////////
    // Copy a . replace element d
    var a1 = {...a, d: {}}
    a1.log -> {b: "b", c: ["c1", "c2"], d: {}}
    
    //////////////////////////////////////////////////////////////////////////////
    // Copy a and copy element d 
    var a1 = {...a, d: {...a.d}}
    a1.log -> {b: "b", c: ["c1", "c2"], d: {d1: "d1", d2: "d2"}}
    a.d === a1.d   // different object
    false
    
    //////////////////////////////////////////////////////////////////////////////
    // Copy a and copy element d and replace d1
    var a1 = {...a, d: {...a.d, d1: 'd3'}}
    a1.log -> {b: "b", c: ["c1", "c2"], d: {d1: "d3", d2: "d2"}}
    
    //////////////////////////////////////////////////////////////////////////////
    // Copy a and copy element d and replace d1 add d4
    var a1 = {...a, d: {...a.d, d1: 'd3', d4: 'd4'}}
    
    a1.log -> {b: "b", c: ["c1", "c2"], d: {d1: "d3", d2: "d2", d4: "d4"}}
    
    //////////////////////////////////////////////////////////////////////////////
    // Deep copy for a
    var d = {}
    var d = {...a, c: [...a.c], d: {...a.d}}
    // because element b is enumerable element we do not need to deep copy b
    d.b === a.b
    true
    a.b = 'b1'
    "b1"
    d.b
    "b"