Pergunta

No ActionScript 3, existe alguma maneira conveniente de determinar se uma matriz associativa (dicionário) tem uma chave particular?

Eu preciso executar lógica adicional se a chave está em falta. Eu poderia capturar a exceção undefined property, mas eu estou esperando que pode ser meu último recurso.

Foi útil?

Solução

var card:Object = {name:"Tom"};

trace("age" in card);  //  return false 
trace("name" in card);  //  return true

Tente este operador: "em"

Outras dicas

hasOwnPropery é uma maneira de testar para ele. Tome este por exemplo:


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

A maneira mais rápida pode ser a mais simples:

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

hasOwnProperty parece ser a solução popular, mas é importante ressaltar que só lida com cordas e pode ser caro para chamar.

Se você estiver usando objetos como chaves em seu dicionário hasOwnProperty não vai funcionar.

A solução mais confiável e alto desempenho é a utilização de igualdade estrita para verificar se há indefinida.

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

Lembre-se de usar igualdade estrita caso contrário entradas com um valor nulo, mas chave válida vão olhar ou seja vazia.

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

E, na verdade, como já foi mencionado usando in deve funcionar bem também

function exists(key:*):Boolean {
    return key in dictionary;
}

Tente isto:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top