1.下面的方法,是给Object的原型(prototype)添加深度复制方法(deep clone)。 1Object.prototype.clone =function() {2//Handle null or undefined or function3if(null==this|| "object" !=typeofthis)4returnthis;5//Handle the 3 simpl
function deepClone(obj) { if (obj === null || typeof obj !== 'object') { return obj; } let clone = obj.constructor(); for (let attr in obj) { if (obj.hasOwnProperty(attr)) { clone[attr] = this.deepClone(obj[attr]); } } return clone; } 优点:对于任何类型的对象都有效,...
constcalendarEvent={title:'abc submit',date:newDate(123),attendees:["Steve",{name:'Steve'}]}constcopied=structuredClone(calendarEvent)copied.attendees.push('Zwan')copied.attendees[1].name='Zwan'console.log(calendarEvent,copied)/* { "title": "abc submit", "date": "1970-01-01T00:00:00.12...
在现代浏览器中,可以使用structuredClone方法来实现深拷贝,它是一种更高效、更安全的深拷贝方式。 以下是一个示例代码,演示如何使用structuredClone进行深拷贝: const kitchenSink = { set: new Set([1, 3, 3]), map: new Map([[1, 2]]), regex: /foo/, deep: { array: [ new File(someBlobData, ...
深拷贝deepClone和浅拷贝Object.assign() /** * 深拷贝 * @param {Object} obj 要拷贝的对象 * obj.hasOwnProperty(key)报错,更改为Object.prototype.hasOwnProperty(obj,key) */ function deepClone(obj = {}) { if (typeof obj !== 'object' || obj == null) {...
functiondeepClone(obj){if(obj===null||typeof obj!=='object'){returnobj;} let clone=obj.constructor();for(let attrinobj){if(obj.hasOwnProperty(attr)){ clone[attr]=this.deepClone(obj[attr]);} }returnclone;} 1. 2. 3. 4.
functionmyDeepClone(obj){letclone;// 排除非引用类型数据if(obj==null||typeofobj!='object')returnobj;if(Array.isArray(obj)){// obj 是数组clone=newobj.constructor(obj.length)obj.forEach((value,index)=>{clone[index]=typeofvalue==='object'?myDeepClone(value):value})}else{// 浅拷贝一份...
'[object Object]' : 'object' }; return map[toString.call(obj)]; } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 实现deepClone 对于非引用值类型的数值,直接赋值,而对于引用值类型(object)还需要再次遍历,递归赋值。
"deep": { "array": [ {} ] }, "error": {}, } 2. 使用递归 代码示例: function deepClone(obj) { if (obj === null || typeof obj !== 'object') { return obj; } let clone = obj.constructor(); for (let attr in obj) { ...
function deepClone(obj) {if (obj === null || typeof obj !== 'object') {return obj;}let clone = obj.constructor();for (let attr in obj) {if (obj.hasOwnProperty(attr)) {clone[attr] = this.deepClone(obj[attr]);}}return clone;} ...