gipouf
gipouf

Reputation: 1241

How to check if an array index exist?

I'm trying to check whether an array index exist in TypeScript, by the following way (Just for example):

var someArray = [];

// Fill the array with data

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

However, i'm getting the following compilation error:

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

Anybody knows why is that? as far as I know, what I'm trying to do is completely legal by JS.

Thanks.

Upvotes: 23

Views: 68972

Answers (4)

Raphael Soares
Raphael Soares

Reputation: 645

One line validation. The simplest way.

if(!!currentData[index]){
  // do something
}

Outputs

var testArray = ["a","b","c"]

testArray[5]; //output => undefined
testArray[1]; //output => "b"

!!testArray[5]; //output => false
!!testArray[1]; //output => true

Upvotes: 2

abahet
abahet

Reputation: 10623

You can also use the findindex method :

var someArray = [];

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

Upvotes: 1

metadept
metadept

Reputation: 7939

As the comments indicated, you're mixing up arrays and objects. An array can be accessed by numerical indices, while an object can be accessed by string keys. Example:

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
}

Upvotes: 34

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

Use hasOwnProperty like this:

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

Upvotes: 11

Related Questions