Reputation: 21
I am trying to sort an array and find which one is bigger. So I have the original array (CurMobRM), an array with the same values but sorted and reversed (Ary) and finaly an array that has the position of the values of the original array (checking).
A quick example is that lets say the original has the values (3,8,5,2,7) and we sort them so we have an array with the same values but in differnt position (8,7,5,3,2) and the final array that have the original position of every value (3,0,2,4,1).
var CurMobRM:Array = new Array (3,8,5,2,7);
var checking:Array= new Array;
putattackorder();
function putattackorder() {
var Ary:Array = CurMobRM;
var lo:Number;
Ary.sort ();
Ary.reverse ();
trace (Ary)
for (lo = 0; lo < 5; lo++) {
for (loop = 0; loop < 5; loop++) {
if (Ary[lo] == CurMobRM[loop]) {
checking[lo] = loop
}
}
}
trace (checking)
trace (Ary)
trace (CurMobRM)
}
The problem is that when I sort the Ary it seems that CurMobRM is also sorted the same time... I dont understand why. The trace(checking) always give 0,1,2,3,4
Upvotes: 0
Views: 76
Reputation: 5693
This happens because in ActionScript 3 array
objects are assigned by reference, not by value. To overcome this you can use the slice
method with no parameters (slice full array).
For example, in your code:
var CurMobRM:Array = new Array (3,8,5,2,7);
var checking:Array= new Array;
putattackorder();
function putattackorder()
{
//perform a copy by value of array
var Ary:Array = CurMobRM.slice();
var lo:uint;
var loop:uint;
Ary.sort();
//not necessary?
//Ary.reverse();
//trace (Ary)
for (lo = 0; lo < 5; lo++) {
for (loop = 0; loop < 5; loop++)
{
if (Ary[lo] == CurMobRM[loop])
{
checking[lo] = loop
}
}
}
trace (checking)
trace (Ary)
trace (CurMobRM)
}
The output is:
3,0,2,4,1
2,3,5,7,8
3,8,5,2,7
Which I believe it is what you are looking for. Hope to help!
Upvotes: 3