AS3 - 是否有可能搜索的数组对象属性? [英] AS3 - Is it possible to search an Array by Object properties?

查看:120
本文介绍了AS3 - 是否有可能搜索的数组对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能使用Array.indexOf()通过一个数组对象的数组中的属性进行搜索:

Would it be possible to use Array.indexOf() to search through an Array by the properties of the Objects within the array:

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

myMovieClip.name = "foo";

myArray.push(myMovieClip);
myArray.indexOf(MovieClip.name == "foo"); //0

myArray.indexOf(myMovieClip.name == "foo"); //0

两者的indexOf()以上不工作,有没有走的正确的语法来实现这一目标?

Both indexOf() above do not work, is there away to achieve this with the correct syntax?

推荐答案

指数将搜索条目... MovieClip.name ==富应该抛出一个编译器错误,因为影片剪辑不具有财产的名字...... myMovieClip.name ==foo的将是真正,然后你会得到真正的指数,如果是在阵列中的所有...

index of will search for an entry ... MovieClip.name == "foo" should throw a compiler error, since MovieClip does not have a property "name" ... myMovieClip.name == "foo" will be true, and then you will get the index of true, if it is in the array at all ...

如果你真的需要索引,则需要通过按键来遍历数组......或增量环,如果数组是数字和密集... 如果数组是联想(使用字符串键),则势在必行需要使用for-in循环,因为对应滤网及相关功能将只包括数字指数...

if you really need the index, you will need to iterate over the array ... by key ... or in an incremental loop, if the array is numeric and dense ... if the array is associative (string keys used) you imperatively need to use for-in loops, since filter and related functions will only cover numeric indices ...

在数值数组,我建议以下两种方法之一:

in a numeric array, i'd suggest one of the following two approaches:

//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" });

希望帮助...;)

hope that helped ... ;)

格尔茨

back2dos

这篇关于AS3 - 是否有可能搜索的数组对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆