每日手写--Object.assign

72 阅读1分钟

Assigns own enumerable string keyed properties of source objects to the destination object. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources. 将两个对象合并,旧的键能够覆盖新的,需要考虑嵌套对象。

  • 实际上是要取两个对象的并集

const o1 = { a: 1, b: 2 };
const o2 = { b: 4, c: 5 };

function merge(target, source) {
//直接遍历这个source,如果target有的就自己保存,如果是source新增的就要把target的给覆盖了 要考虑嵌套对象的话需要递归处理
  for (let key in source) {
    if (typeof target[key] === 'object' && typeof source[key] === 'object') {
        merge(target[key], source[key])
    } else {
        target[key] = source[key]
    }
  }
  return target
}
const o = merge(o1, o2)
console.log(o) //{ a: 1, b: 4, c: 5 }

//最开始犯的错误是重新创一个新的对象的时候 只遍历了后面的source 但是没有考虑到target自身的属性也应该包含在内,取得是并集

function merge(target, source) {
    let res = {}
    for (let key in target) {
        if (typeof target[key] =='object'&& typeof source[key] == 'object') {
           res =  merge(target[key], source[key])
        } else {
           res[key] = source[key] || target[key]
        }
    }
    for (let key in source) {
        res[key] = source[key]
    }
    return res
}
const keys = Object.keys(obj); //获取所有key 

时间复杂度:O(n + m),其中n是target对象的属性个数,m是source对象的属性个数。 空间复杂度:O(n + m),其中n是target对象的属性个数,m是source对象的属性个数。