美文网首页
每日一条JS精华片段:deepClone

每日一条JS精华片段:deepClone

作者: _夏之_ | 来源:发表于2020-09-06 15:33 被阅读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

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

相关文章

网友评论

      本文标题:每日一条JS精华片段:deepClone

      本文链接:https://www.haomeiwen.com/subject/vzycektx.html