2012-03-30 72 views
0

我想过滤的数组中返回仅有1项返回一个项目 我的代码是从滤波阵列

private function audioProgress(event:Event):void{ 
     var wordindex:int=0; 
     function filterFun(element:int, index:int, array:Array):Boolean { 
      return (element < soundChannel.position); 
     } 
     var arr:Array=soundPositions.filter(filterFun); 
} 

我想要的“改编”到只包含一个项目 我怎样才能做到这一点

回答

1

如果我正确读取了你的代码,你试图同步到播放声音?然后使用Array.filter是效率低下 - 你只需要跟踪最近通过的标记。

假设你soundPositions阵列数字顺序排序,这可以在一个简单的循环来完成:

这样一来,只会有数组的一个迭代 - 总。 while循环从当前索引开始,并且当该值大于或等于声音的位置时它将会退出,因此current将始终指向(虚拟)播放头已经通过的最后一个项目。

+0

非常感谢 – JustMe 2012-03-31 09:12:58

1

你需要你想要的物品的索引。如果你只想要第一个项目,请使用:

arr[0]; 
0

另一变型从初始阵列得到一个项目:

private function audioProgress(event:Event):void{ 
     var wordindex:int=0; 
     var firstRequiredItemIndex:int = -1; 
     function filterFun(element:int, index:int, array:Array):Boolean { 
      if (element < soundChannel.position) 
      { 
       firstRequiredItemIndex = index; 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 

     if (soundPositions.some(filterFun)) 
     { 
      // Your element 
      soundPositions[firstRequiredItemIndex]; 
     } 
} 

函数“一些”上的每个项目阵列中的,直到达到一个项目,则返回true执行测试功能。所以不需要检查整个数组。

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#some%28%29

+0

功能将始终从开头的阵列环,不过,由于声音的位置,随着时间的增加,迭代将越来越长。 – weltraumpirat 2012-03-31 06:35:05