Domanda

Voglio creare un array associativo:

var aa = {} //equivalent to Object(), new Object(), etc...

e voglio essere sicuro che qualsiasi tasto accedo sta per essere un numero:

aa['hey'] = 4.3;
aa['btar'] = 43.1;

So JS non ha digitazione, quindi non posso controllare automaticamente questo, ma posso assicurare nel mio codice che ho assegnare solo le stringhe a questo aa.

Ora sto prendendo le chiavi da parte dell'utente. Voglio visualizzare il valore per quella chiave. Tuttavia, se l'utente mi dà qualcosa come "toString", che sarà lui a tornare una funzione, non un int! C'è un modo per assicurarsi che qualsiasi stringa che mi dà è solo qualcosa che mi definisco? È l'unica soluzione qualcosa come:

delete aa['toString'];
delete aa['hasOwnProperty'];

ecc ...

È stato utile?

Soluzione

Sarà questo lavoro per voi?

function getValue(id){
  return (!isNaN(aa[id])) ? aa[id] : undefined;
}

Aggiornamento:

Con l'aiuto di Moss Collum e pottedmeat Consiglio questo soluzione generica:

function getValue(hash,key) {
    return Object.prototype.hasOwnProperty.call(hash,key) ? hash[key] : undefined;
}

Update2: Aveva dimenticato il ".Call". (Grazie pottedmeat per la segnalazione)

Update3: (Informazioni sui tasti)

Si noti la seguente: La chiave sarà internamente convertito in una stringa perché la chiave è in realtà un nome di un attributo.

var test = {
  2:"Defined as numeric", 
  "2":"Defined as string" 
}  

alert(test[2]); //Alerts "Defined as string"

Se si cerca di utilizzare un oggetto:

var test={}, test2={};
test[test2]="message"; //Using an object as a key.

alert(test[test2]); //Alerts "message". Looks like it works...

alert(test[  test2.toString() ]);
//If it really was an object this would not have worked,
// but it also alerts "message".

Ora che sapete che è sempre una stringa, consente di usarlo:

var test={};

var test2={
    toString:function(){return "some_unique_value";}
    //Note that the attribute name (toString) don't need quotes.
}

test[test2]="message";
alert(test[ "some_unique_value"] ); //Alerts "message".

Altri suggerimenti

Una possibilità sarebbe quella di utilizzare hasOwnProperty per verificare che la chiave è qualcosa che si aggiunge esplicitamente alla matrice. Così, invece di:

function findNumber(userEnteredKey) {
    return aa[userEnteredKey];
}

che ci si dice:

function findNumber(userEnteredKey) {
    if (Object.prototype.hasOwnProperty.call(aa,userEnteredKey))
        return aa[userEnteredKey];
}

In alternativa, è possibile utilizzare typeof per controllare che tutto è un numero prima di restituirlo. Ma mi piace l'approccio hasOwnProperty, perché ti terrà dal ritornare tutto ciò che non hai intenzionalmente messo nella matrice.

risposta molto semplice: quando si crea una nuova chiave di anteporre con una costante stringa di tua scelta.

var a = {};
var k = 'MYAPP.COLLECTIONFOO.KEY.';

function setkey(userstring)
{
  a[k+userstring] = 42;
}

function getkey(userstring)
{
  return a[k+userstring];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top