2012-02-17 98 views
0

我想創建一個函數來比較兩個數組並返回找到的項目的索引。如果我的例子數組是:as3比較兩個數組並返回索引

var distances:Array = new Array (0,275,217,385,275,0,251); 
var selectedDist:Array = new Array (217,275,251); 

我想它返回2,4,6

+0

爲什麼你返回索引4的距離爲275?爲什麼不只是1? – sch 2012-02-17 23:36:07

回答

1

嘗試以下操作:

var indices:Array = []; 

for each(var distance:int in selectedDist) { 
    var index:int = distances.indexOf(distance); 
    if (index >= 0) { 
     indices.push(index); 
    } 
} 

return indices; 
+0

謝謝.......偉大..除了索引:array.push(索引),應該是indices.push(索引)...乾杯 – 2012-02-17 23:44:13

+0

是的抱歉,我直接在這裏鍵入代碼,所以我沒有注意到那。我在編輯我的答案。 – sch 2012-02-17 23:46:42

0

假如你總是selectedDist陣列比較距離陣列,我會這樣做:

protected function compareArrays(arr1:Array, arr2:Array):Array 
{ 
    var matches:Array = new Array(); 

    for(var x:int=0; x < arr2.length; x++) { 
    /* 
    * indexOf returns -1 id the element is not found in the array 
    * http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#indexOf() 
    * but you have to grab the lastIndexOf 275, as requested... 
    */ 
    if (arr1.indexOf(arr2[x] > -1)) 
     matches.push(arr1.lastIndexOf(arr2[x])); 
    } 

    return matches; 
}