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
    }
  • 相关阅读:
    使用contentProvider
    创建Sqlite数据库(一)
    AIDL实现进程间通信
    Messenger实现进程间通信(IPC)
    Serializable使用
    Parcelable使用(二)
    STAR法则
    Python系列-------基本语法
    前端随心记---------面试题集
    前端随心记---------惟客科技面试
  • 原文地址:https://www.cnblogs.com/lml2017/p/10691123.html
Copyright © 2011-2022 走看看