From e6891f9baa93c2bcc266b04ec0682872e862e410 Mon Sep 17 00:00:00 2001 From: YangJ0605 <1442122744@qq.com> Date: Tue, 19 May 2020 10:56:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=AF=8F=E6=97=A5=E5=AD=A6=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- deepclone.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 deepclone.js diff --git a/deepclone.js b/deepclone.js new file mode 100644 index 0000000..7fbde95 --- /dev/null +++ b/deepclone.js @@ -0,0 +1,38 @@ +function _type(value) { + return Object.toString.call(value).slice(8,-1).toLocaleLowerCase() +} + +function deepclone(obj) { + if(obj === null) return null + if(typeof obj !== 'object') return obj + if(_type(obj) === 'regexp') return new RegExp(obj) + if(_type(obj) === 'date') return new Date(obj) + const newObj = new obj.constructor + for(const key in obj) { + if(obj.hasOwnProperty(key)) { + let item = obj[key] + newObj[key] = deepclone(item) + } + } + return newObj +} + +function deepclone2(obj) { + if(typeof obj !== 'object' || obj === null) return + let newObj = new obj.constructor + for(let key in obj) { + if(obj.hasOwnProperty(key)) { + let item = obj[key],itemType = _type(item) + if(item !== null && typeof item === 'object') { + if(/(regexp|date)/.test(itemType)) { + newObj[key] = new item.constructor(item) + continue + } + newObj[key] = deepclone2(item) + continue + } + newObj[key] = item + } + return newObj + } +} \ No newline at end of file