1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| const syb = Symbol('str') const person = { syb, name: 'name', age: 18, un: undefined, nu: null, is: true, date: new Date(), arr: [1, 2, 3, 4], fu: function () { console.log('123') }, re: /\d/gi, o: { a: 1, b: '3', c: true } } console.log('person', person) const test = JSON.parse(JSON.stringify(person)) console.log('test', test)
function copyRegExp(regExp) { let attrs = ''; if (regExp.global) attrs += 'g'; if (regExp.ignoreCase) attrs += 'i'; if (regExp.multiline) attrs += 'm'; let newRegExp = new RegExp(regExp, attrs); newRegExp.lastIndex = regExp.lastIndex; return newRegExp; }
function getDataType(data) { return Object.prototype.toString.call(data).slice(8, -1) }
function deepCopy(obj) { if (obj === null || typeof obj !== 'object') return obj switch (getDataType(obj)) { case 'Date': console.log() return new Date(obj.getTime()) case 'Function': return obj case 'RegExp': return copyRegExp(obj) default: let result = Array.isArray(obj) ? [] : {} for (const key in obj) { result[key] = deepCopy(obj[key]) } return result } } const deep = deepCopy(person) console.log('deep', deep)
|