-
Notifications
You must be signed in to change notification settings - Fork 769
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
46 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,35 @@ | ||
// 判断arr是否为一个数组,返回一个bool值 | ||
function isArray (arr) { | ||
return Object.prototype.toString.call(arr) === '[object Array]'; | ||
function isArray(arr) { | ||
return Object.prototype.toString.call(arr) === '[object Array]'; | ||
} | ||
|
||
// 深度克隆 | ||
function deepClone (obj) { | ||
// 对常见的“非”值,直接返回原来值 | ||
if([null, undefined, NaN, false].includes(obj)) return obj; | ||
if(typeof obj !== "object" && typeof obj !== 'function') { | ||
//原始类型直接返回 | ||
return obj; | ||
} | ||
var o = isArray(obj) ? [] : {}; | ||
for(let i in obj) { | ||
if(obj.hasOwnProperty(i)){ | ||
o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i]; | ||
} | ||
} | ||
return o; | ||
function deepClone(obj, cache = new WeakMap()) { | ||
if (obj === null || typeof obj !== 'object') return obj; | ||
if (cache.has(obj)) return cache.get(obj); | ||
let clone; | ||
if (obj instanceof Date) { | ||
clone = new Date(obj.getTime()); | ||
} else if (obj instanceof RegExp) { | ||
clone = new RegExp(obj); | ||
} else if (obj instanceof Map) { | ||
clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])); | ||
} else if (obj instanceof Set) { | ||
clone = new Set(Array.from(obj, value => deepClone(value, cache))); | ||
} else if (Array.isArray(obj)) { | ||
clone = obj.map(value => deepClone(value, cache)); | ||
} else if (Object.prototype.toString.call(obj) === '[object Object]') { | ||
clone = Object.create(Object.getPrototypeOf(obj)); | ||
cache.set(obj, clone); | ||
for (const [key, value] of Object.entries(obj)) { | ||
clone[key] = deepClone(value, cache); | ||
} | ||
} else { | ||
clone = Object.assign({}, obj); | ||
} | ||
cache.set(obj, clone); | ||
return clone; | ||
} | ||
|
||
|
||
export default deepClone; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters