ES6扩展运算符(三点运算符)“...”用法和对象拷贝

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)
相关文章
相关标签/搜索