直接等号赋值相当于添加了一个指针指向该内存
当你修改赋值后的数据,原来的数据也会发生改变(),如下
let obj = {name:"1",age:"10"}
let obj2 = obj
obj2.name = '2'
console.log(obj)
打印结果: {name: '2', age: '10'}
当你循环赋值的时候,开辟一个新的堆内存,两个内存不会有关联(深拷贝)
let obj = {name:"1",age:"10"}
let obj2 = {}
for(let key in obj){
obj2[key] = obj[key]
}
obj2.age = 1000
console.log(obj)
console.log(obj2)
VM1358:7 {name: '1', age: '10'}
VM1358:8 {name: '1', age: 1000}
最后贴一段深拷贝的代码
/**
* 对象深拷贝
*/
export const deepClone = (data) => {
var type = getObjType(data);
var obj;
if (type === "array") {
obj = [];
} else if (type === "object") {
obj = {};
} else {
// 不再具有下一层次
return data;
}
if (type === "array") {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]));
}
} else if (type === "object") {
for (var key in data) {
obj[key] = deepClone(data[key]);
}
}
return obj;
};
获取对象类型getObjType
export const getObjType = (obj) => {
var toString = Object.prototype.toString;
var map = {
"[object Boolean]": "boolean",
"[object Number]": "number",
"[object String]": "string",
"[object Function]": "function",
"[object Array]": "array",
"[object Date]": "date",
"[object RegExp]": "regExp",
"[object Undefined]": "undefined",
"[object Null]": "null",
"[object Object]": "object",
};
if (obj instanceof Element) {
return "element";
}
return map[toString.call(obj)];
};
网友评论