Copying Arrays in JS

var original = [true,true,undefined,false,null];

//slice()
var copy1 = original.slice(0);
console.log(copy1); // [true,true,undefined,false,null]

//spread operator
//just spreads out this original array into wherever we're putting it
//so spread out the original array into the new array
var copy2 = [...original];
console.log(copy2); // [true,true,undefined,false,null]

//the above does not always work if you have an array or an object within your array
//上面的数组中的元素都是原生数据类型的,但是如果数组中是非原生类型的,比如元素是数组(即二维数组),或是对象
//此时上面的方法将会出问题。解决办法是要用「deep copying」
var deepArray = [["freeCodeCamp"]];
var shallowArray = deepArray.slice(0);

shallowArray[0].push("is great");
console.log(deepArray[0]); // ["freeCodeCamp", "is great"]
console.log(shallowArray[0]); // ["freeCodeCamp", "is great"]

可以看到上面两个输出的结果是一样,这不是我们期望的,也就是说当我改了shallowArray的第一个元素后,
这个改动会直接影响到deepArray上面,这就是问题,而我们期望的是只有shallowArray的第一个元素变成`["freeCodeCamp", "is great"]`,
而deepArray的第一个元素仍然是`["freeCodeCamp"]`才对。
简单分析下原因:
the reason is because anytime you have an array within an array in JS 
or you have an object within an array in JS, 
in the original array is just a pointer to an array or a pointer to an object inside that original array, 
so when we are doing a copy of the array we're just copying the pointers to that original array, 
when we push "is great", we're not pushing "is great" to the shallowCopy directly, 
we're pushing "is great" to the pointer to the other array and since both of them are pointing to the same array

解决方法:
你可以用loops去做,但是代码会相对较多,there is actually a trick,
it's a secret way that makes it a lot easier

var deepCopy = JSON.parse(JSON.stringify(deepArray));
//the `JSON.stringify()` is going to create a string of the whole array including an array within the array and objects with an array
//then `JSON.parse()` is going to convert this string back into a JS object or JS array

deepCopy[0].push("is great");
console.log(deepArray[0]); // ["freeCodeCamp"]
console.log(deepCopy[0]); // ["freeCodeCamp", "is great"]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值