es6拷貝數組對象有如下方法:es6
方法一: Object.assign() // 對象淺拷貝,obj1複製給obj2 const obj1 = {a: 1}; const obj2 = {}; Object.assign( obj2, obj1) 方法二 :ES6擴展運算符(...) //對象深拷貝,obj1複製給obj2 const obj1 = {a: 1}; const obj2 = {...obj1}; 方法三 :深拷貝 //對象深拷貝,obj1複製給obj2 const obj1 = {a: 1}; const obj2 = JSON.parse(JSON.stringify(obj1));
所謂深拷貝和淺拷貝:數組
const obj1 = {a: 1}; const obj2 = obj1 obj2.a = 2 console.log(obj1) //{a:2}
像這種直接賦值的方式實際上是obj2引用obj1,兩者指向同一個堆存儲地址,不管改變哪個兩者都會受影響。數據結構
對於簡單數組對象(不含有引用數據類型),能夠用淺拷貝方法來消除這種關聯影響。函數
對於複雜數組對象(含有引用數據類型,好比:{a:1,b:[1,2,3],c:{d:3}} 多層嵌套類型的),則須要用深拷貝方法。this
在實際項目中,一般會這樣:lua
this.selectEvaluate({param: param, showLoading: true}).then((res) => { if (res.data) {
console.log(res.data) this.evaluationInfo = res.data } else { ... } })
console.log打印出來會發現res.data數據結構發生了一些變化,多了一些對象的get和set函數,這樣的直接賦值是一種引用,雖然不會對數據產生出bug,可是若是其餘地方也須要使用到res.data,像這樣的:spa
this.selectEvaluate({param: param, showLoading: true}).then((res) => { if (res.data) { console.log(res.data) this.evaluationInfo = res.data this.selectEvaluationInfo = res.data } else { ... } })
這種狀況下須要用對象拷貝方法來區分,能夠使用三點運算符寫法比較簡便:code
this.selectEvaluate({param: param, showLoading: true}).then((res) => { if (res.data) { console.log(res.data) this.evaluationInfo = {...res.data} this.selectEvaluationInfo = {...res.data} } else { ... } })
拷貝對象只是三點運算符的一種用法,它還有其餘多種用法,經常使用於數組序列化:對象
function f(x, y, z) { // ... } var args = [0, 1, 2]; f(...args)