Come determinare se un array associativo ha una chiave?
-
22-08-2019 - |
Domanda
In ActionScript 3, c'è un modo conveniente di determinare se un array associativo (dizionario) ha una chiave particolare?
Ho bisogno di eseguire logica aggiuntiva se la chiave non è presente. Ho potuto intercettare l'eccezione undefined property
, ma spero che possa essere la mia ultima risorsa.
Soluzione
var card:Object = {name:"Tom"};
trace("age" in card); // return false
trace("name" in card); // return true
Prova questo operatore: "in"
Altri suggerimenti
hasOwnPropery
è un modo di testare per esso. Prendete questo esempio:
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"));
Il modo più veloce può essere la più semplice:
// 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 sembra essere la soluzione popolare, ma vale la pena sottolineando che si occupa solo nelle stringhe e possono essere costosi da chiamare.
Se stai usando oggetti come chiavi nel dizionario hasOwnProperty non funzioneranno.
La soluzione più affidabile e performante è quello di utilizzare una rigorosa parità per verificare indefinito.
function exists(key:*):Boolean {
return dictionary[key] !== undefined;
}
Ricordate di usare uguaglianza rigorosa altrimenti le voci con un valore nullo, ma chiave valida guarderà cioè vuota.
null == undefined // true
null === undefined // false
E in realtà, come è stato detto con in
dovrebbe funzionare bene anche
function exists(key:*):Boolean {
return key in dictionary;
}
Prova questo:
for (var key in myArray) {
if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}