A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: surprised when I copy an array ...

  1. #1
    Senior Member
    Join Date
    Oct 2007
    Location
    Leeds, UK
    Posts
    118

    surprised when I copy an array ...

    Just wondering if anybody else finds this surprising:

    Code:
    var master:Array = [5,6,7,8,9];
    var copy:Array = master;
    
    trace(copy); // 5,6,7,8,9
    trace(master); // 5,6,7,8,9
    copy[2] = 1001;
    trace(copy);  // 5,6,1001,8,9
    trace(master);  // 5,6,1001,8,9 (original also changed)
    So I need to do things this way, and then everything works fine:
    Code:
    var master:Array = [5,6,7,8,9];
    var copy:Array = [master[0],master[1],master[2],master[3],master[4]];
    trace(copy); // 5,6,7,8,9
    
    copy[2] = 1001;
    trace(copy);  // 5,6,1001,8,9
    trace(master);  // 5,6,7,8,9  (original untouched)
    So arrays behave very differently from 'normal' variables:
    Code:
    var master:int = 56;
    var copy:int = master;
    
    copy = 1001;
    trace(copy); // 1001
    trace(master); // 56
    Is this a 'Flash' thing, or do most programming languages work in this way?
    Just wondering, that's all.

  2. #2
    FK'n_dog a_modified_dog's Avatar
    Join Date
    Apr 2003
    Location
    "aaarf"
    Posts
    9,176
    to copy an array use the Array.concat method.
    the original array is left unchanged.
    PHP Code:
    var master:Array = [5,6,7,8,9];
    var 
    copy:Array = [];

    copy master.concat();

    copy[2] = 1001;
    trace(copy);
    trace(master); 

  3. #3
    Senior Member
    Join Date
    Oct 2007
    Location
    Leeds, UK
    Posts
    118
    Thank You, a_modified_dog.

    That's useful.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center