ReferenceError #1065: can not create property 0 on … (and #1069)
Last week, I was trying to create a shuffle function on my array class which extends the native Array class. I got the ReferenceError when running the code bellow. The reason is that Array is a dynamic class and my is not. Since Array is dynamic, it will try to create new property when you try to assign some value to a nonexistent instance variable but MyArray prevents this. If you try this you will see that reference error #1065 is occurred when the array is constructed. If you remove the constructor you will get reference error #1069 instead and it hapens when you try to swap the elements in shuffle method (trying to access a nonexistent instance variable). So make sure that you declare dynamic if you extend a dynamic class or better if editor or compiler gives a warning if you forget …
package vnmedia.common.lang { import vnmedia.common.lang.math.Random; public class MyArray extends Array { public function MyArray(...parameters) { super(parameters); } public function shuffle():void { var a:*, k:int, i:int, r:Random = new Random(); for(i = this.length; i > 1; i--){ // 0 <= k <= i - 1 k = r.nextInt(i); a = this[k]; this[k] = this[i-1]; this[i-1] = a; } } } }
However, I think the best way to provide a shuffle function for arrays is to define a static ArrayUtil.shuffle as bellow
package vnmedia.common.lang { import vnmedia.common.lang.math.Random; public class ArrayUtil { public function ArrayUtil() { } public static function shuffle(arr:Array):void { var a:*, k:int, i:int, r:Random = new Random(); for(i = arr.length; i > 1; i--){ k = r.nextInt(i); a = arr[k]; arr[k] = arr[i-1]; arr[i-1] = a; } } } }