Copying Arrays in JS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stanxl/article/details/80960225
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"]

猜你喜欢

转载自blog.csdn.net/stanxl/article/details/80960225