switching places within an Array() using XOR

switching places 

This small function switches places of two array elements. Very useful and quick. I’ve needed to write this for a simple aplication that uses layers (like the photoshop ones) and changes the places of elements in the layer when the user moves the layer to a different depth :)

 Here it is:

var my_array:Array = new Array(12,3,55,24);
function swap_indexes(a,b)
{
 my_array[a] ^= my_array[b];
 my_array[b] ^= my_array[a];
 my_array[a] ^= my_array[b];
 trace(my_array); // 55,3,12,24
};
swap_indexes(0,2); // these are the two array indexes you want to switch place

The above works both in AS2 and AS3 - Hope it helps someone :)

Of course the above method works only with Numbers. If you want to use it with different variable types like String you should use the old and slow method.

It would look like this (works both AS2 and AS3):

var my_array:Array = new Array(”mike”,”dan”,”jeremy”,”chris”);
var t:String;
function swap_indexes(a,b)
{
 t=my_array[a];
 my_array[a] = my_array[b];
 my_array[b] = t;
 trace(my_array); // “jeremy”,”dan”,”mike”,”chris”
};
swap_indexes(0,2); // these are the two array indexes you want to switch place

FLAIM