vue添加對象數(shù)據(jù)到數(shù)組,前面添加的所有數(shù)據(jù)都會變成最后一個添加的對象
這是因為對象數(shù)據(jù)為引用數(shù)據(jù)類型,簡單的push方法添加對象到數(shù)組的時候,只是把對象的地址指針重復(fù)的給到數(shù)組的每一項,也就是數(shù)組的每一項數(shù)據(jù)都指向了同一個對象,對象數(shù)據(jù)一變,數(shù)組所有數(shù)據(jù)都跟著變。
解決辦法就是要push不同地址的對象到數(shù)組里面去,讓數(shù)組的每一項數(shù)據(jù)都指向不同地址的對象,方法是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'
? ? ? ? ? ? }
? ? ? ? }
}