js数组、对象、数组中套对象等的“复制”(不改变原来的值)的方法,

数组

1:数组用concat

  let a=[1,2,3]
   let b=a.concat()
    a[0]=1000
    console.log(a)
    console.log(b)
值为:
 [1000, 2, 3]
 [1, 2, 3]

 2:数组用Object.assign()

let a=[1,2,3]
let b=Object.assign([],a)
a[0]=1000
console.log(a)
console.log(b)
值为:
[1000, 2, 3]
[1, 2, 3]

对象

对象用Object.assign()

let a={age:12,name:'寅春树'}
let b=Object.assign({},a)
a.age=50
console.log(a)
console.log(b)
值为:
{age: 50, name: "寅春树"}
{age: 12, name: "寅春树"}

杀手锏:数组中有对象

let a=[1,2,3,{age:12,name:"寅春树"}]
let b=JSON.parse(JSON.stringify(a))
a[0]=100
a[3].age=50
console.log(a)
console.log(b)
值为:


posted @ 2020-04-27 12:38  寅春树  阅读(1694)  评论(0编辑  收藏  举报