AS3 - 是否可以搜索Array by Object属性?

RVa*_*ine 6 actionscript-3

是否可以使用Array.indexOf()通过数组中对象的属性搜索数组:

var myArray:Array = new Array();
var myMovieClip = new MovieClip();

myMovieClip.name = "foo";

myArray.push(myMovieClip);
myArray.indexOf(MovieClip.name == "foo"); //0 
Run Code Online (Sandbox Code Playgroud)

要么

myArray.indexOf(myMovieClip.name == "foo"); //0
Run Code Online (Sandbox Code Playgroud)

上面的indexOf()都不起作用,是否有正确的语法实现这一点?

bac*_*dos 3

index of 将搜索条目 ... MovieClip.name == "foo" 应该抛出编译器错误,因为 MovieClip 没有属性 "name" ... myMovieClip.name == "foo" 将为true,并且那么你将得到 true 的索引,如果它在数组中的话......

如果您确实需要索引,则需要通过键迭代数组...或者在增量循环中,如果数组是数字且密集的...如果数组是关联的(使用字符串键)您绝对需要使用 for-in 循环,因为过滤器和相关函数将仅覆盖数字索引......

在数字数组中,我建议采用以下两种方法之一:

//this will return an array of all indices
myArray.map(function (val:*,index:int,...rest):int { return (val.name == "foo") ? index : -1 }).filter(function (val:int,...rest):Boolean { return val != -1 });

//here a more reusable utility function ... you may want to put it to some better place ... just as an example ...
package {
     public class ArrayUtils {
          public static function indexOf(source:Array, filter:Function, startPos:int = 0):int {
               var len:int = source.length;
               for (var i:int = startPos; i < len; i++) 
                    if (filter(source[i],i,source)) return i;
               return -1;
          }
     }
}
//and now in your code:
var i:int = ArrayUtils.indexOf(myArray, function (val:*,...rest):Boolean { return val.name == "foo" });
Run Code Online (Sandbox Code Playgroud)

希望有帮助...;)

格雷茨

后退2dos