You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
658 B

3 years ago
  1. // 判断arr是否为一个数组,返回一个bool值
  2. function isArray (arr) {
  3. return Object.prototype.toString.call(arr) === '[object Array]';
  4. }
  5. // 深度克隆
  6. function deepClone (obj) {
  7. // 对常见的“非”值,直接返回原来值
  8. if([null, undefined, NaN, false].includes(obj)) return obj;
  9. if(typeof obj !== "object" && typeof obj !== 'function') {
  10. //原始类型直接返回
  11. return obj;
  12. }
  13. var o = isArray(obj) ? [] : {};
  14. for(let i in obj) {
  15. if(obj.hasOwnProperty(i)){
  16. o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
  17. }
  18. }
  19. return o;
  20. }
  21. export default deepClone;