Copy array by value

2018-12-30 23:21发布

When copying an array in JavaScript to another array:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

30条回答
路过你的时光
2楼-- · 2018-12-30 23:48

For ES6 array containing objects

cloneArray(arr) {
    return arr.map(x => ({ ...x }));
}
查看更多
若你有天会懂
3楼-- · 2018-12-30 23:51

Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.

var arr2 = new Array(arr1);

Now arr1 and arr2 are two different array variables stored in separate stacks. Check this out on jsfiddle.

查看更多
栀子花@的思念
4楼-- · 2018-12-30 23:53
let a = [1,2,3];

Now you can do any one of the following to make a copy of an array.

let b = Array.from(a); 

OR

let b = new Array(...a); 

OR

let b = a.slice(); 

OR

let b = a.map(e => e);

Now, if i change a,

a.push(5); 

Then, a is [1,2,3,5] but b is still [1,2,3] as it has difference reference.

But i think, in all the methods above Array.from is better and made mainly to copy an array.

查看更多
残风、尘缘若梦
5楼-- · 2018-12-30 23:54

You can use array spreads ... to copy arrays.

const itemsCopy = [...items];

Also if want to create a new array with the existing one being part of it:

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];

Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.

More info on spreads

查看更多
与风俱净
6楼-- · 2018-12-30 23:55

Here are few more way to copy:

const array = [1,2,3,4];

const arrayCopy1 = Object.values(array);
const arrayCopy2 = Object.assign([], array);
const arrayCopy3 = array.map(i => i);
const arrayCopy4 = Array.of(...array );

查看更多
时光乱了年华
7楼-- · 2018-12-30 23:56

If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:

var arr1 = ['a','b','c'];
var arr2 = [...arr1]; //copy arr1
arr2.push('d');

console.log(arr1)
console.log(arr2)
<script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>

查看更多
登录 后发表回答