471,854 Members | 1,375 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,854 software developers and data experts.

array.slice() not creating an independent copy.

Alright, am I missing something?

I create a 2D array like so:

var blah = [];
blah[0] = ['one', 'two', 'three'];
blah[1] = ['four', 'five', 'six'];

Then I *attempt* to create an independent copy based on all of the pages I have read that
said it was as so:

var copy_of_blah = blah.slice(); // does not create independent copy
var copy_of_blah = blah.slice(0); // nor does this

I tested it by immediately changing either:

blah[0][0] = ''; // "one" is now ''

*or*

copy_of_blah[0][0] = ''; // "one", is again, ''

And of course both reflect changes upon the other.

Is it possible to create an independent copy of an array without having to write a
function that dumps the contents into a new array?

-Lost
Mar 11 '07 #1
2 3701
On Mar 11, 4:59 pm, "-Lost" <missed-s...@comcast.netwrote:
[...]
Is it possible to create an independent copy of an array without having to write a
function that dumps the contents into a new array?
Only if the elements of the array are primitives, where you can use
concat. If you have an array of arrays and use slice, your 'copy'
consists of an array of references to the arrays in the original
array.
--
Rob

Mar 11 '07 #2
"RobG" <rg***@iinet.net.auwrote in message
news:11**********************@8g2000cwh.googlegrou ps.com...
On Mar 11, 4:59 pm, "-Lost" <missed-s...@comcast.netwrote:
[...]
>Is it possible to create an independent copy of an array without having to write a
function that dumps the contents into a new array?

Only if the elements of the array are primitives, where you can use
concat. If you have an array of arrays and use slice, your 'copy'
consists of an array of references to the arrays in the original
array.
Primitives, as in no Objects.

Thanks, RobG.

-Lost
Mar 11 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by kr | last post: by
4 posts views Thread by Christopher Benson-Manica | last post: by
1 post views Thread by Antony Sequeira | last post: by
7 posts views Thread by RubyRedRick | last post: by
NeoPa
reply views Thread by NeoPa | last post: by
reply views Thread by YellowAndGreen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.