-
[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?
-
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.
-
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.
-
You can use an empty .concat() to generate a copy of the first array:
PHP Code:
const TEST_ARRAY:Array = [1, 2, 3, 4, 5, 6];
var reverseArray:Array = TEST_ARRAY.concat().reverse();
-
or slice() with no arguments (this will also create a copy of an array).
-
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|