js对象clone

  1. 浅拷贝,如果对象的属性值是数或者字符串则值传递,否则为引用传递
function clone(obj){
    return {...obj};
}
or
function clone(obj){
    return Object.assign({},obj);
}
var t1 = {a: 'hello', b:[0, 1]}
var t2 = clone(t1);
t1.a = 'world';
console.log(t1.a, t2.a); // world hello
t1.b[0] = -1
console.log(t1.b[0], t2.b[0]); // -1 -1
  1. deepClone
function clone(obj) {
    var newobj = obj.constructor === Array ? [] : {};
    if (typeof obj !== "object") {
        return obj;
    } else {
        for (var i in obj) {
            newobj[i] = typeof obj[i] === "object" ? clone(obj[i]) : obj[i];
        }
    }
    return newobj;
}
  • 在存在Symbol类型属性key时,无法正确拷贝
function clone(obj) {
    return JSON.parse(JSON.stringify(obj);
}

  • Set 类型、Map 类型以及 Buffer 类型会被转换成 {}
  • undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)
  • 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误
  1. 结构化克隆,第一种推荐,参考JavaScript 深拷贝性能分析
function StructuredClone(param) {
  return new Promise(function (res, rej) {
    const {port1, port2} = new MessageChannel();
    port2.onmessage = ev => res(ev.data);
    port1.postMessage(param);
  })
}
StructuredClone(objects).then(result => console.log(result))
function structuralClone(obj) {
  const oldState = history.state;
  history.replaceState(obj, document.title);
  const copy = history.state;
  history.replaceState(oldState, document.title);
  return copy;
}
const clone = structuralClone(objects);
function structuralClone(obj) {
  return new Notification('', {data: obj, silent: true}).data;
}

const obj = /* ... */;
const clone = structuralClone(obj);

你可能感兴趣的:(js对象clone)