常用的浅拷贝实现方法

常用的浅拷贝实现方法

Object.assign

ES6中拷贝对象的方法,接受的第一个参数是拷贝的目标target,剩下的参数是拷贝的源对象sources(可以是多个)

let target = {};
let source = {
	a: '123',
	b: {
		name: 'javascript'
	}
}
Object.assign(target,source);
console.log(target); // {a:'123',b:{name:'javascript'}}

Object.assign使用注意事项:

  • 只拷贝源对象的自身属性(不拷贝继承属性)
  • 不会拷贝对象不可枚举的属性
  • undefined和null无法转成对象,他们不能作为Object.assign参数,但是可以作为源对象
  • 属性名为Symbol 值的属性,可以被Object.assign拷贝

Array.prototype.slice

let array = [{a:1},{b:2}]
let array1 = array.slice(0);
console.log(array1)
  • slice:从已有的数组中返回选定的元素

Array.prototype.concat

let array = [{a:1},{b:2}]
let array1 = [].concat(array)
console.log(array1)

扩展运算符

let obj = {a:1,b:{c:1}}
let obj2 = {...obj}
console.log(obj2)
posted @ 2020-08-01 11:43  清梦徐徐丶莫  阅读(604)  评论(0编辑  收藏  举报