zoukankan      html  css  js  c++  java
  • 深拷贝一个对象/数组 的方法封装

    export function deepClone (source) {
      // 类型校验,如果不是引用类型 或 全等于null,直接返回
      if (source === null || typeof source !== 'object') {
        return source
      }
    
      let isArray = Array.isArray(source)
      let result = isArray ? [] : {}
    
      // 遍历属性
      if (isArray) {
        for (let i = 0, len = source.length; i < len; i++) {
          let val = source[i]
          // typeof [] === 'object', typeof {} === 'object'
          // 考虑到 typeof null === 'object' 的情况, 所以要加个判断
          if (val && typeof val === 'object') {
            result[i] = deepClone(val)
          } else {
            result[i] = val
          }
        }
        // 简写
        // result = source.map(item => {
        //     return (item && typeof item === 'object') ? deepCopy(item) : item
        // });
      } else {
        const keys = Object.keys(source)
        for (let i = 0, len = keys.length; i < len; i++) {
          let key = keys[i]
          let val = source[key]
          if (val && typeof val === 'object') {
            result[key] = deepClone(val)
          } else {
            result[key] = val
          }
        }
        // 简写
        // keys.forEach((key) => {
        //     let val = source[key];
        //     result[key] = (val && typeof val === 'object') ? deepCopy(val) : val;
        // });
      }
    
      return result
    }
  • 相关阅读:
    主流浏览器标签默认样式一览
    为什么要清除默认样式?
    php 的空间命名以及对对象的相关操作,扩展到对数据库的相关函数
    js string
    js基础
    ubuntu-desktop
    php 时期相关函数
    字符串,验证码
    function 相关
    ubuntu_soft相关安装
  • 原文地址:https://www.cnblogs.com/lml2017/p/10691123.html
Copyright © 2011-2022 走看看