guangchao.xu | 070005a | 2020-12-07 09:56:40 +0800 | [diff] [blame^] | 1 | // 判断arr是否为一个数组,返回一个bool值 |
| 2 | function isArray (arr) { |
| 3 | return Object.prototype.toString.call(arr) === '[object Array]'; |
| 4 | } |
| 5 | |
| 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; |
| 21 | } |
| 22 | |
| 23 | export default deepClone; |