2013-03-31 14 views
16

Sto cercando di verificare se esiste un indice di array a macchina, dal seguente senso (solo per esempio):Typescript - Come verificare se esiste un indice di array?

var someArray = []; 

// Fill the array with data 

if ("index" in someArray) { 
    // Do something 
} 

Tuttavia, sto ottenendo il seguente errore di compilazione:

The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type

Qualcuno sa perché è così? per quanto ne so, quello che sto cercando di fare è completamente legale da JS.

Grazie.

+2

Si deve usare un oggetto, non un array. – SLaks

+0

"indicizza" una stringa o un indice numerico effettivo? – elclanrs

+0

una stringa. Immagino che farò come ha detto SLaks, ho pensato che anche gli array di dattiloscritti possono essere usati anche come array associativi. – gipouf

risposta

29

come i commenti indicati, si sta mescolando array e gli oggetti. È possibile accedere a un array mediante indici numerici, mentre è possibile accedere a un oggetto mediante chiavi stringa. Esempio:

var someObject = {"someKey":"Some value in object"}; 

if ("someKey" in someObject) { 
    //do stuff with someObject["someKey"] 
} 

var someArray = ["Some entry in array"]; 

if (someArray.indexOf("Some entry in array") > -1) { 
    //do stuff with array 
} 
+0

C'è un opposto dell'operatore in? – Devid

+0

logico, se (! ("SomeKey" in someObject)) – AgBorkowski

3

jsFiddle Demo

Usa hasOwnProperty come questo:

var a = []; 
if(a.hasOwnProperty("index")){ 
/* do something */ 
} 
1

È anche possibile utilizzare il metodo FindIndex:

var someArray = []; 

if(someArray.findIndex(x => x === "index") >= 0) { 
    // foud someArray element equals to "index" 
} 
Problemi correlati