我自己常用的几个JS深浅拷贝的方法
程序员文章站
2024-02-22 22:31:28
...
案例代码
let obj = [ { name: 'robin', age: 24, num: [ { sleep: '8', eat: 'chicked', happy: [1,2,3] } ] } ]
深拷贝
- JSON
let newObj = JSON.parse(JSON.stringify(obj))
- jQuery的$.extend()
let o = {} let newObj = $.extend(true, o, obj)
- 函数库lodash里面的closeDeep方法
- 递归拷贝
function deepClone (sourceObj, targetObj) { let cloneObj = targetObj || {} if(!sourceObj || typeof sourceObj !== "object" || sourceObj.length === undefined){ return sourceObj } if(sourceObj instanceof Array){ cloneObj = sourceObj.concat() // concat 不会改变原有数组,会返回原有数组的一个副本 } else { for(let i in sourceObj){ if (typeof sourceObj[i] === 'object') { cloneObj[i] = deepClone(sourceObj[i], {}) } else { cloneObj[i] = sourceObj[i] } } } return cloneObj }
浅拷贝
- Object.create()
- Object.assign()
- 引用赋值