你應該認爲sortOn()
排序的元素中的陣列按照陣列中的屬性注意。該陣列應該具有以下特徵:
- 該數組是一個索引數組,而不是關聯數組。
- 該陣列的每個元素都包含具有一個或多個屬性的object。
- 所有對象至少有共同的一個屬性,其值可用於排序數組。
那麼,這是一個數組:
var a:Array = ["a", "b", "c"]
這是一個對象(又名關聯陣列):
var o:Object = {"name":"Tom", "age":21, "single":true}
這是結構的類型sortOn()
方法適用於:
var a:Array = [
{"name":"Tom", "age":21, "single":true},
{"name":"Dick", "age":36, "single":false},
{"name":"Harry", "age":27, "single":true}
]
此外,當您聲明一個變量的模式是NAME:TYPE = VALUE
,而不是NAME = TYPE
下面是相應的代碼。你已經添加了print()
函數,它追蹤出數組的內容,以便你可以看到前後的數據。
/* --- Code that wasn't provided --- */
// This creates the data so we can test sorting it.
var genotype:Array = [];
for (var r:int = 0; r < 16; r++) {
var row:Array = [];
for (var c:int = 0; c < 4; c++) {
row.push(Math.floor(Math.random() * 100));
}
genotype.push(row)
}
var fitness:Array = [];
/* --- Modified Original Code --- */
// Loop through the genotype, and create entries in fitness with the sum and index
for (var i:int = 0; i < genotype.length; i++) {
fitness[i] = {"sum":sumArray(genotype[i]), "index":i};
}
function sumArray(a:Array):Number {
// This simply adds up the total values in an array.
var sum:int = 0;
for (var i:int = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
fitness.sortOn("sum", Array.NUMERIC); // Sort on the sum property, numerically ascending.
// To sort the original data, I'm going to place it into a new array.
var newGeno:Array = [];
i = 0;
for each (var entry:Object in fitness) {
newGeno[i] = genotype[entry.index];
i++;
}
/* If you want, you can replace the original, simply add...
genotype = newGeno;
*/
trace("--- GENOTYPE ---")
print(genotype);
trace("--- NEW GENO ---")
print(newGeno);
function print(a:Array, prefix:String = ""):void {
for (var i:int = 0; i < a.length; i++) {
if (a[i] is Array) {
trace(prefix + i + ": [Array] " + sumArray(a[i]));
print(a[i], prefix + " ");
} else {
trace(prefix + i + ": " + a[i])
}
}
}