A Flash Developer Resource Site

Results 1 to 6 of 6

Thread: [RESOLVED] Array.reverse() is changing a constant!

  1. #1
    Owned By Code
    Join Date
    Feb 2001
    Posts
    151

    resolved [RESOLVED] Array.reverse() is changing a constant!

    Alright maybe I'm on the short-bus here, but I thought the whole purpose of a constant variable was so that it doesn't change.

    Now I can work around the issue, but I thought it was important to note.

    Steps to reproduce:

    Create a constant array
    - public static const TEST_ARRAY:Array = new Array(1, 2, 3, 4, 5, 6);

    Make a new variable that would be the array's reverse - var reverseArray:Array = TEST_ARRAY.reverse();

    Trace the results - trace(TEST_ARRAY, reverseArray);

    RESULTS:

    6, 5, 4, 3, 2, 1
    6, 5, 4, 3, 2, 1

    Is this a bug or am I missing a better function to reverse the order of my array?

  2. #2
    Ө_ө sleepy mod
    Join Date
    Mar 2003
    Location
    Oregon, USA
    Posts
    2,441
    Two things - first, when you store an array to a variable, you're not making a new array, just saving a reference. So in your example both TEST_ARRAY and reverseArray are the same object in memory.

    Secondly, storing an object in a constant (eg. anything that's not a primitive or a literal) does not make it immutable. You can't put a new Array into that constant but you can modify the one that's there. On the same logic, you can put a bitmapData into a constant and still use the .draw() command - since it's the same bitmap, you're just altering the pixels.

  3. #3
    Owned By Code
    Join Date
    Feb 2001
    Posts
    151
    Thanks for the reply, just sucks that reverse() is destructive instead of creating a new reference. I had to write some lame loop to re-write the array backwards which seemed pretty stupid. Oh well.

  4. #4
    Ө_ө sleepy mod
    Join Date
    Mar 2003
    Location
    Oregon, USA
    Posts
    2,441
    You can use an empty .concat() to generate a copy of the first array:

    PHP Code:
    const TEST_ARRAY:Array = [123456];
    var 
    reverseArray:Array = TEST_ARRAY.concat().reverse(); 

  5. #5
    Junior Member
    Join Date
    Aug 2008
    Posts
    26
    or slice() with no arguments (this will also create a copy of an array).

  6. #6
    Owned By Code
    Join Date
    Feb 2001
    Posts
    151
    Thanks nez and wvx ( I ended up using the concat method ) that worked out great.

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