数组浅拷贝的方式

首先

let arr1 = [1, 2, 3];
let arr2 = arr1;

肯定是不行的

记录一下几种简单的方法.

let arr2 = [...arr1];
let arr2 = arr1.concat();
let arr2 = arr1.slice();

顺便写一下自己写的对象深拷贝的方法,

const test = {
  info: {
    name: 'kobe',
    nums: [1,2,3]
  }
}

test.loop = test;

function isObj(obj) {
  return typeof obj === 'object' && obj !== null;
}

// weakSet防止循环引用
function deepClone(source, set = new WeakSet) {
  console.log(source);
  if(set.has(source)) {
    return source;
  }
  const obj = Array.isArray(source) ? [] : {};
  set.add(source);
  for(let key in source) {
    obj[key] = isObj(source[key]) ? deepClone(source[key], set) : source[key];
  }
  return obj;
}

let new_test = deepClone(test);
test.info.nums.push(4);
console.log(new_test);


// JSON方式能实现简单的深拷贝,但是无法解决循环引用。
// 在JSON.stringify的时候很多规则会使最后JSON.parse出来的对象不太一样。
// 例如会忽略undefined,总的说转成JSON字符串的时候,要让大多数语言理解,就不能存在undefined, NaN这种
const person1 = {
  name: 'hello',
  gender: 'male'
}
const person2 = null;
const json_obj = {
  info: {
    name: 'kobe',
    nums: [1,2,3]
  },
  persons: [person1, person2]
}

let obj = JSON.parse(JSON.stringify(json_obj));
console.log(obj);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值