【问题标题】:AS3 accessing object attributesAS3 访问对象属性
【发布时间】:2012-09-10 18:39:09
【问题描述】:

我试图弄清楚是否有办法将对象存储在数组类型的数据结构中,然后能够在所有对象中搜索特定属性。

例如,如果我有四个对象存储在一个数组中(它们的名称是 object1-4),并且它们都有一个 ID 属性(object1.ID = 1, object2.ID = 2, object3.ID = 3, object4.ID = 4) ,有没有办法搜索数组的所有对象(object1-4)以找到与数字匹配的对象ID?

例如,如果我的数组包含 [object1, object2, object3, object4] 并且它们都具有 ID 属性 (object1.ID = 1, object2.ID = 2, object3.ID = 3, object4.ID = 4)我正在尝试找到一种方法来遍历所有对象以查找 ID 为 2 的对象

var objectList:Array = new Array;
objectList[0] = object1;
objectList[1] = object2;
objectList[2] = object3;
objectList[3] = object4;

function searchArray(searchTerm:int)
{
    if(var i:int = 0; i <  objectList.length ; i++)
    {
       if(objectList[i].ID == searchTerm)
       {  
          trace("Match Found")
       }
    }
}

【问题讨论】:

  • 如果您的所有 objectList 项目都属于相同的对象类型,您应该使用 Vector 而不是数组。

标签: arrays actionscript-3 arraylist


【解决方案1】:
    function searchArray(searchTerm:int,searchBy:String = 'ID'):*
    {
        var res:* = null;
        for(var i:int = 0; i <  objectList.length ; i++)
        {
            if(objectList[i].hasOwnProperty(searchBy))
            {
                if(objectList[i][searchBy] == searchTerm)
                {  
                    res = objectList[i];
                    break;
                }
            }

        }
        return res;
    }

【讨论】:

    【解决方案2】:

    如果您的ID = object2 和您的搜索词是2,您将永远不会匹配==。尝试任一:

    if (Number(objectList[i].ID.replace('object', '')) == searchterm) { ... }
    

    if (objectList[i].ID == 'object' + searchterm) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多