数组与对象的深拷贝
对象
//1
var newObject = JSON.parse(JSON.stringify(oldObject));
//2
function clone(obj) {
if (obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
return obj;
if (obj instanceof Date)
var temp = new obj.constructor(); //or new Date(obj);
else
var temp = obj.constructor();
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null;
temp[key] = clone(obj[key]);
delete obj['isActiveClone'];
}
}
return temp;
}
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
数组
let a=[1,2,3]
let b=a.slice();
let c=a.concat();//或者使用ES7 let c = [...a],转码后也是concat
console.log(a === b)//false
console.log(a === c)//false
网友评论