as3比较两个数组并返回索引

时间:2012-02-17 22:56:11

标签: arrays actionscript-3 compare indexing

我想创建一个比较2个数组并返回找到的项目索引的函数。例如,我的数组是:

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

我希望它返回2,4,6

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}