zoukankan      html  css  js  c++  java
  • JavaScript之 深浅拷贝 Better

    测试的对象:

    const obj1 = {
        name: 'xxx',
        age: 20,
        address: {
            city: '北京'
        },
        arr: ['a', 'b', 'c']
    }

    浅拷贝:

    // 1. 遍历
    function simpleClone (oldObj) {
      var newObj = {}
      for(var i in oldObj) {
        newObj[i] = oldObj[i]
      }
      return newObj
    }
    
    // 2. Object.creat()形式
    var obj2 = Object.create(obj1)
    
    // 3. 直接拷贝
    const obj2 = obj1
    
    // 测试
    obj2.address.city = '上海'
    consloe.log(obj1.address.city) // 上海

    深拷贝:

    /**
     * 深拷贝
     * @param {Object} obj 要拷贝的对象
     */
    function deepClone(obj = {}) {
        if (typeof obj !== 'object' || obj == null) {
            // obj 不是对象和数组,或者是 null,直接返回
            return obj
        }
    
        // 初始化返回结果
        let result
        if (obj instanceof Array) {
            result = []
        } else {
            result = {}
        }
    
        for (let key in obj) {
            // 保证 key 不是原型的属性
            if (obj.hasOwnProperty(key)) {
                // 递归调用 (重点)
                result[key] = deepClone(obj[key])
            }
        }
    
        // 返回结果
        return result
    }
  • 相关阅读:
    C#入门(3)
    C#入门(2)
    C#入门(1)
    JNI工程搭建及编译
    Java-NestedClass(Interface).
    ConCurrent in Practice小记 (4)
    Java Annotation 注解
    Android使用ViewPager做轮播
    ConCurrent in Practice小记 (3)
    ConCurrent in Practice小记 (2)
  • 原文地址:https://www.cnblogs.com/huangtq/p/14457866.html
Copyright © 2011-2022 走看看