|
1 | 1 | // 判断arr是否为一个数组,返回一个bool值
|
2 |
| -function isArray (arr) { |
3 |
| - return Object.prototype.toString.call(arr) === '[object Array]'; |
| 2 | +function isArray(arr) { |
| 3 | + return Object.prototype.toString.call(arr) === '[object Array]'; |
4 | 4 | }
|
5 | 5 |
|
6 | 6 | // 深度克隆
|
7 |
| -function deepClone (obj) { |
8 |
| - // 对常见的“非”值,直接返回原来值 |
9 |
| - if([null, undefined, NaN, false].includes(obj)) return obj; |
10 |
| - if(typeof obj !== "object" && typeof obj !== 'function') { |
11 |
| - //原始类型直接返回 |
12 |
| - return obj; |
13 |
| - } |
14 |
| - var o = isArray(obj) ? [] : {}; |
15 |
| - for(let i in obj) { |
16 |
| - if(obj.hasOwnProperty(i)){ |
17 |
| - o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i]; |
18 |
| - } |
19 |
| - } |
20 |
| - return o; |
| 7 | +function deepClone(obj, cache = new WeakMap()) { |
| 8 | + if (obj === null || typeof obj !== 'object') return obj; |
| 9 | + if (cache.has(obj)) return cache.get(obj); |
| 10 | + let clone; |
| 11 | + if (obj instanceof Date) { |
| 12 | + clone = new Date(obj.getTime()); |
| 13 | + } else if (obj instanceof RegExp) { |
| 14 | + clone = new RegExp(obj); |
| 15 | + } else if (obj instanceof Map) { |
| 16 | + clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])); |
| 17 | + } else if (obj instanceof Set) { |
| 18 | + clone = new Set(Array.from(obj, value => deepClone(value, cache))); |
| 19 | + } else if (Array.isArray(obj)) { |
| 20 | + clone = obj.map(value => deepClone(value, cache)); |
| 21 | + } else if (Object.prototype.toString.call(obj) === '[object Object]') { |
| 22 | + clone = Object.create(Object.getPrototypeOf(obj)); |
| 23 | + cache.set(obj, clone); |
| 24 | + for (const [key, value] of Object.entries(obj)) { |
| 25 | + clone[key] = deepClone(value, cache); |
| 26 | + } |
| 27 | + } else { |
| 28 | + clone = Object.assign({}, obj); |
| 29 | + } |
| 30 | + cache.set(obj, clone); |
| 31 | + return clone; |
21 | 32 | }
|
22 | 33 |
|
| 34 | + |
23 | 35 | export default deepClone;
|
0 commit comments