0

Adobe Array 文档中的示例不是很直观...

如果我有一个具有和Card属性的对象,我该如何重写这段代码以寻找具有特定值的可见卡片?strvisiblestr

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;
}
4

1 回答 1

2

类的some(), every()(and forEach()) 方法Array有两个参数:

  • callback在每个项目上执行的函数,它应该根据您的条件返回 true 或 false
  • thisObjectthis是一个可选对象,您可以提供给回调函数,在函数内部您可以使用关键字引用该对象。如果省略此参数,则可以使用回调函数形成闭包。

回调函数的签名如下:

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;
}
于 2012-08-11T19:21:20.250 回答