+ 6
Javascript Array
I want to copy a two dimensional array by value, not by reference. I tried "var arr2 = arr1.slice();" but it didn't work. When I do this for example, it changes arr1 and arr2. var arr1 =[[1,2], [3,4]]; var arr2 = [arr1[0], arr1[1]]; arr2[0][1]=5; So my question is: How do I copy a two dimensional array by value in Javascript?
7 Antworten
+ 9
@tim Since, array is not a basic data type every element contains a reference In case of array of arrays.
So you need to do like this I guess:
https://code.sololearn.com/WMAbJHh5SAK9/?ref=app
+ 6
arr1.slice() will work.
You have used I guess arr1.splice()
+ 6
@Ashwani thank you very much!
@Mohammad, change "arr2[0]" to "arr2[0][0]" then you see what I mean :-|
+ 5
Example code in playground please
+ 4
@Tim, it seems slice() also use reference for inner array.
However you can use a little trick here.
first convert the arr1 to string then convert it back to a new array and assign it to arr2 variable.
Check out the updated code..
https://code.sololearn.com/Wm9VYi97J2VB/?ref=app
+ 3
Use slice() method like this,
var arr2 = arr1.slice()