每日一条JS精华片段:deepClone

2020-09-06  本文已影响0人  _夏之_

创建对象的深层克隆。克隆基本值,数组和对象

Javascript方法

const deepClone = obj => {
  if (obj === null) return null;
  let clone = Object.assign({}, obj);
  Object.keys(clone).forEach(
    key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
  );
  if (Array.isArray(obj)) {
    clone.length = obj.length;
    return Array.from(clone);
  }
  return clone;
};

示例

const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a);

执行结果

 a !== b, a.obj !== b.obj

请关注我,每天获得一条精华小片段!

上一篇 下一篇

猜你喜欢

热点阅读