=='object'||obj===null){returnobj;}letcopy={};// 如果对象是数组if(obj.constructor===Array){copy=[];}// 遍历对象的每个属性for(letkinobj){// 如果 key 是对象的自有属性if(obj.hasOwnProperty(k)){// 递归调用 deepClonecopy[k]=deepClone(obj[k]);}}
function deepClone(obj, hash = new WeakMap()) { if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj !== 'object' || obj === null) return obj; if (hash.has(obj)) return hash.get(obj); let t = new obj.const...
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 simple types, Number and String and Boolean6if(thisinstanceofNumber ||th...
[Javascript] structuredClone - deep clone object 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": "a...
# deepClone(object = {})object <Object> 需要被克隆的对象let a = { name: 'mary' }; // 直接赋值,为对象引用,即修改b等于修改a,因为a和b为同一个值 let b = a; b.name = 'juli'; console.log(b); // 结果为 {name: 'juli'} console.log(a); // 结果为 {name: 'juli'} // ...
1、工具集isObject function isObject(object) { return object !== null && typeof object === 'object'; } 2、算法:回溯法,递归 functiondeepCloneWithCircle(source){constset=newWeakSet();constresult=deepCloneWithCircleImpl(source,set);// todo 如果不支持WeakSet则使用数组,在这里清空数组。returnresul...
js手写deepClone深拷贝 背景 实际开发中,处理数据经常会使用到数据拷贝。其实使用JSON.stringify()与JSON.parse()来实现深拷贝是很不错的选择。 但是当拷贝的数据为undefined,function(){}等时拷贝会为空,这时就需要采用递归拷贝。 使用JSON实现拷贝时,注意拷贝数据,看是否适合使用。
clone = clone || [] : clone = clone || {} for (const i in obj) { if (typeof obj[i] === 'object' && obj[i]!==null) { // 要考虑深复制问题了 if (Array.isArray(obj[i])) { // 这是数组 clone[i] = [] } else { // 这是对象 clone[i] = {} } deepClone(obj[i]...
js中的deepClone克隆函数function deepClone(obj) { var _toString = Object.prototype.toString;// null, undefined, non-object, function if (!obj || typeof obj !== 'object') { return obj;} // DOM Node if (obj.nodeType && 'cloneNode' in obj) { return obj.cloneNode(true);} // Date ...
简介:JavaScript 自己实现深拷贝 (deep clone) JSON.parse() constnewObj =JSON.parse(JSON.stringify(obj)); 局限性: 无法实现对函数,正则表达式等特殊对象的克隆 会抛弃对象的 constructor,所有的构造函数会指向 Object 对象有循环引用会报错 简单手写版 ...