We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
通过哈希表保存已经拷贝过的对象,再次遇到相同对象属性时,直接从哈希表中取出,避免出现死循环。
/** * 深拷贝 * * @export * @param {*} source * @param {*} [hash=new WeakMap()] * @returns */ export function deepClone(source: any, hash = new WeakMap()) { // 非 object 对象直接原值返回 if (typeof source !== 'object' || source === null) { return source } // 从 hash 表中查找对象是否已经拷贝过 // 如果已经拷贝过,直接取出该值返回 if (hash.has(source)) return hash.get(source) // 分别处理 array 和 object const target: any = Array.isArray(source) ? [] : {} // 将 source 遍历后生成的 target 保存进 hash 表 hash.set(source, target) // 遍历 source 对象的属性 Reflect.ownKeys(source).forEach(key => { if (typeof source === 'object' && source !== null) { // 如果是 object 类型,递归调用 deepClone target[key] = deepClone(source[key], hash) } else { // 非 object 类型原值赋值 target[key] = source[key] } }) return target }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
能处理循环引用的深拷贝
通过哈希表保存已经拷贝过的对象,再次遇到相同对象属性时,直接从哈希表中取出,避免出现死循环。
The text was updated successfully, but these errors were encountered: