splice returns an array!
— 29th April 2009
This one caught me out for a long time today.
I have an array of Objects which I want to jumble up a bit. AS3 doesn't come with a randomise (or randomize in the US!) function so I Googled around a bit to find one. The following came from some site somewhere and is no doubt a very well intentioned piece of code.
function randomizeArray(array:Array):Array { var newArray:Array = new Array(); while(array.length > 0) { newArray.push(array.splice(Math.floor(Math.random()*array.length), 1)); } return newArray; }So, you can kind of see what it’s doing right. Take an array. While your way through it removing one item at a time by choosing a random item using the length of the array. Each time the length of the array shortens by one. You add each item to a new array and once your old array is empty return your newly random array. Sweet!
Only splice returns an array! Splice returns an array!! Do you hear?
So your newly randomised array isn't full of your objects it’s full of lots of little arrays each containing one item which is your object. This is not fine. You try and do anything with those items (inside their arrays) and you can't. Cos they're inside arrays.
Which would be fine if you realised they were inside arrays... but I didn't.
Took me ages to work it out, because when you trace the blasted things out the way Flash traces single item arrays makes it look like it’s the object itself. You don't see that it’s inside an array.
sigh