常用的淺拷貝實現方法
1,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拷貝
2,Array.prototype.slice
let array = [{a:1},{b:2}] let array1 = array.slice(0); console.log(array1)
slice:從已有的數組中返回選定的元素
3,Array.prototype.concat
let array = [{a:1},{b:2}] let array1 = [].concat(array) console.log(array1)
4,擴展運算符
let obj = {a:1,b:{c:1}} let obj2 = {...obj} console.log(obj2)
參考:https://www.cnblogs.com/justyouadmin/p/13413990.html