普通物件
1、Object.assign({}, obj);
var a = {'name': 'xiaoyu'};
var b = Object.assign({}, a);
b.name = 'xiaoyu2';
console.log(a.name);//xiaoyu2
複製程式碼
2、JSON.parse(JSON.stringify(obj))
var a = {'name': 'xiaoyu'};
var b = JSON.parse(JSON.stringify(a));
b.name = 'xiaoyu2';
console.log(a.name);//xiaoyu2
複製程式碼
3、for迴圈賦值
var extentObj = function(obj1,obj2){
//遍歷obj2中屬性
for(let key in obj2){
//判斷obj1不存在此屬性
if(obj2.hasOwnProperty(key) && (!obj1.hasOwnProperty(key))){
//將此值賦給obj1
obj1[key] = obj2[key]
}
}
}
複製程式碼
4、擴充套件運算子
var a = {'name': 'xiaoyu'};
var { ...b } = a;
b.name = 'xiaoyu2';
console.log(a.name);//xiaoyu2
複製程式碼
物件陣列
1、for迴圈賦值
var arr = {
userName:"xiaoyu",
roles:[{id:1},{id:2}]
}
//或
//var arr = {
// userName:"xiaoyu",
// role:{
// id:1,
// name:"管理員"
// }
//}
var arr2 = objDeepCopy(arr);
function objDeepCopy(arr) {
let res = {};
for (let key in arr) {
if(typeof arr[key] === 'object'){ //判斷是否是物件型別
if(arr[key] instanceof Array){ //進一步判斷是否是陣列
res[key] = [];
for(let item of arr[key]){
res[key].push(objDeepCopy(item)); //遞迴判斷當前值
}
}else{
res[key] = objDeepCopy(arr[key]);
}
}else{
res[key] = arr[key];
}
}
return res
}
arr.roles[0].id = 4;
console.log(arr); //{name:"xiaoyu2",roles:[{id:4},{id:2}]
console.log(arr2); //{name:"xiaoyu",roles:[{id:1},{id:2}]
複製程式碼
普通陣列
1、for迴圈賦值
var arr = [1,2,3,4,5]
var arr2 = copyArr(arr)
function copyArr(arr) {
let res = []
for (let i = 0; i < arr.length; i++) {
res.push(arr[i])
}
return res
}
複製程式碼
2、slice方法
var arr = [1,2,3,4,5]
var arr2 = arr.slice(0)
arr[2] = 5
console.log(arr)
console.log(arr2)
複製程式碼
3、concat 方法
var arr = [1,2,3,4,5]
var arr2 = arr.slice(0)
arr[2] = 5
console.log(arr)
console.log(arr2)
複製程式碼
4、ES6擴充套件運算子
var arr = [1,2,3,4,5]
var [ ...arr2 ] = arr
arr2[2] = 5
console.log(arr)
console.log(arr2)
複製程式碼