the Adobe Array doc中的示例不是很直观......
如果我的Card
对象具有属性str
和visible
,如何重写这段代码以查找具有特定str
值的可见卡?
FOUND:
for each (var str:String in newHand) {
for each (card in hand) {
if (card.visible && str == card.str)
continue FOUND;
}
// there is a new card - redraw the whole hand
redrawHand(owner);
break;
}
答案 0 :(得分:2)
some()
类的every()
,forEach()
(和Array
)方法有两个参数:
callback
对每个项目执行的函数,它应该根据您的条件返回true或false thisObject
是一个可以提供给回调函数的可选对象,在函数内部可以使用this
关键字引用该对象。如果省略此参数,则可以使用回调函数形成闭包。回调函数的签名如下:
private var callback:Function = function(currentItem:Object, currentIndex:int, theEntireArray:Array):Boolean
{
// your logic here returns true/false based on your critera
}
对于您的方案,也许您可以使用some()
方法,如下所示:
private var comparisonString:String;
private function showTheExampleCode()
{
for each (var str:String in newHand)
{
// comparisonString will be used in the closure
// maybe you can just use str in the closure instead?
comparisonString=str;
if (hand.some(callback))
{
// at least one match was found, do something
}
}
}
private var callback:Function(currentItem:Object, currentIndex:int, array:Array):Boolean
{
// current item is a Card object (you probably do not have to cast it)
return Card(currentItem).visible && Card(currentItem).str == comparisonString;
}