js中物件引用,淺拷貝,深拷貝--示例
阿新 • • 發佈:2018-11-09
1. 物件引用
var a = {name:'wanger'}
var b = a ;
a===b // true
b.name = 'zhangsan'
a.name //'zhangan'
2 .淺拷貝
var a = {name:'wanger'}
var b = Object.assign({}, a)
a===b // false
b.name = 'zhangsan'
a.name //'wanger'
2.參考別人示例程式碼
var obj = {a: 1, b: 2, c: { a: 3 },d: [4, 5]} var obj1 = obj var obj2 = JSON.parse(JSON.stringify(obj))//深拷貝常用方法 var obj3 = {...obj} var obj4 = Object.assign({},obj) obj.a = 999 obj.c.a = -999 obj.d[0] = 123 console.log(obj1) //{a: 999, b: 2, c: { a: -999 },d: [123, 5]} console.log(obj2) //{a: 1, b: 2, c: { a: 3 },d: [4, 5]} console.log(obj3) //{a: 1, b: 2, c: { a: -999 },d: [123, 5]} console.log(obj4) //{a: 1, b: 2, c: { a: -999 },d: [123, 5]}
var arr = [1, 2, 3, [4, 5], {a: 6, b: 7}] var arr1 = JSON.parse(JSON.stringify(arr))//深拷貝常用方法 var arr2 = arr var arr3 = [...arr] var arr4 = Object.assign([],arr) console.log(arr === arr1) //false console.log(arr === arr2) //true console.log(arr === arr3) //false console.log(arr === arr4) //false arr[0]= 999 arr[3][0]= -999 arr[4].a = 123 console.log(arr1) //[1, 2, 3, [4, 5], {a: 6, b: 7}] console.log(arr2) //[999, 2, 3, [-999, 5], {a: 123, b: 7}] console.log(arr3) //[1, 2, 3, [-999, 5], {a: 123, b: 7}] console.log(arr4) //[1, 2, 3, [-999, 5], {a: 123, b: 7}]