cothedo Posted December 14, 2008 Share Posted December 14, 2008 I have a multi-dimensional array variable that I need to copymyArray1[x][y] and myArray2[x][y]Now, I can't just do this: myArray1 = myArray2The new array will only create a reference to the original array (In other words, when I change a value in the new array, the original will also be changed). For a single dimensional array, you can use the "slice" method to copy an array, without it becoming a reference to the original. But how can you use "slice" for multi-dimensional arrays? I tried to google it, but couldn't find anything. Link to comment Share on other sites More sharing options...
jesh Posted December 15, 2008 Share Posted December 15, 2008 How about something along these lines: for(var i = 0; i < myArray1.length; i++){ myArray2[i] = myArray1[i].slice(0);} Link to comment Share on other sites More sharing options...
jeffman Posted December 15, 2008 Share Posted December 15, 2008 Interestingly, Jesh's method seems to work no matter what gets stored in the array variables. I tried this where one of the second-order array variables held a two-dimensional object, and everything copied just fine. I had imagined some hideously recursive method, but it looks like you only have to go one level deep in order to grab everything. Link to comment Share on other sites More sharing options...
rnd me Posted December 15, 2008 Share Posted December 15, 2008 loops are slow, and you don't need one here. myArray2 = myArray1.concat();will do exactly what you want in a lot less time and code.i fell in love with the trick as soon as i saw it a while back... Link to comment Share on other sites More sharing options...
jeffman Posted December 15, 2008 Share Posted December 15, 2008 Sweet! <smacks self on forehead> Link to comment Share on other sites More sharing options...
rnd me Posted December 16, 2008 Share Posted December 16, 2008 background info for nerds:in fact, r2=r1.slice(); should do the same thing...the above slice example (post #2) worked because slice returns a new array, as does concat... Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.