vue添加对象数据到数组,前面添加的所有数据都会变成最后一个添加的对象
这是因为对象数据为引用数据类型,简单的push方法添加对象到数组的时候,只是把对象的地址指针重复的给到数组的每一项,也就是数组的每一项数据都指向了同一个对象,对象数据一变,数组所有数据都跟着变。
解决办法就是要push不同地址的对象到数组里面去,让数组的每一项数据都指向不同地址的对象,方法是push之前深拷贝要添加的对象。
function deepClone(data) {
let obj = null
let type = getObjType(data)
console.log(type);
if (type == 'array') {
obj = []
} else if (type == 'object') {
obj = {}
} else {
return data
}
if (type == 'array') {
for (let index = 0; index < data.length; index++) {
obj.push = deepClone(data[index]);
}
return obj
} else if (type == 'object') {
for (const key in data) {
obj[key] = deepClone(data[key]);
}
return obj
}
}
function getObjType(data) {
let type = typeof(data)
if (type == 'object') {
let is_arr = data instanceof Array
if (is_arr) {
return 'array'
}else {
return 'object'
}
} else {
if (type == 'string') {
return 'string'
} else if (type = 'number') {
return 'number'
} else if (type = 'boolean') {
return 'boolean'
}else if (type = 'undefined') {
return 'undefined'
}
}
}