代码之家  ›  专栏  ›  技术社区  ›  Soviut

如何确定关联数组是否有键?

  •  21
  • Soviut  · 技术社区  · 16 年前

    在ActionScript3中,是否有任何方便的方法来确定关联数组(字典)是否具有特定的键?

    如果钥匙丢失,我需要执行额外的逻辑。我可以抓住 undefined property 例外,但我希望这是我最后的选择。

    5 回复  |  直到 12 年前
        1
  •  37
  •   Cotton    16 年前
    var card:Object = {name:"Tom"};
    
    trace("age" in card);  //  return false 
    trace("name" in card);  //  return true
    

    试试这个接线员:“in”

        2
  •  5
  •   Soviut    13 年前

    hasOwnPropery 是你测试的一种方法。例如:

    
    var dict: Dictionary = new Dictionary();
    
    // this will be false because "foo" doesn't exist
    trace(dict.hasOwnProperty("foo"));
    
    // add foo
    dict["foo"] = "bar";
    
    // now this will be true because "foo" does exist
    trace(dict.hasOwnProperty("foo"));
    
        3
  •  4
  •   Theo.T    16 年前

    最快的方法可能是最简单的:

    // creates 2 instances
    var obj1:Object = new Object();
    var obj2:Object = new Object();
    
    // creates the dictionary
    var dict:Dictionary = new Dictionary();
    
    // adding the first object to the dictionary (but not the second one)
    dict[obj1] = "added";
    
    // checks whether the keys exist
    var test1:Boolean = (dict[obj1] != undefined); 
    var test2:Boolean = (dict[obj2] != undefined); 
    
    // outputs the result
    trace(test1,test2);
    
        4
  •  2
  •   Mike Stead    12 年前

    hasownProperty似乎是一个流行的解决方案,但值得指出的是,它只处理字符串,调用起来可能很昂贵。

    如果将对象用作字典中的键,那么hasownproporty将不起作用。

    更可靠和性能更高的解决方案是使用严格的等式检查未定义。

    function exists(key:*):Boolean {
        return dictionary[key] !== undefined;
    }
    

    请记住使用严格的等同性,否则具有空值但有效键将看起来为空,即。

    null == undefined // true
    null === undefined // false
    

    实际上,正如前面提到的,使用 in 也应该工作得很好

    function exists(key:*):Boolean {
        return key in dictionary;
    }
    
        5
  •  1
  •   evilpenguin    16 年前

    试试这个:

    for (var key in myArray) {
        if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
    }