1.浅拷贝
// 浅拷贝
let shallowCopy = function (obj) {
if (typeof obj !== 'object') return
let newObj = obj instanceof Array ? [] : {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key]
}
}
return newObj
}
2.深拷贝
// 递归深拷贝
let deepCopy = function (obj) {
if (typeof obj !== 'object') return
let newObj = obj instanceof Array ? [] : {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj
}
// 入栈深拷贝
let cloneDeep = function (obj) {
let root = Array.isArray(obj) ? [] : {};
let stack = [{
parent: root,
key: undefined,
data: obj
}]
while (stack.length) {
let node = stack.pop()
let parent = node.parent
let key = node.key
let data = node.data
// 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素
let res = parent;
if (typeof key !== 'undefined') {
res = parent[key] = Array.isArray(data)? [] : {};
}
for (let k in data) {
if(data.hasOwnProperty(k)) {
if (typeof data[k] === 'object') {
stack.push({parent: res, key: k, data: data[k]})
} else {
res[k] = data[k];
}
}
}
}
return root
}