Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array index exist?

Tags:

javascript

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.

like image 561
gipouf Avatar asked Mar 31 '13 20:03

gipouf


People also ask

How do you check if an array exists?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How do I check if an array is index php?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.

How do you check if an array does not exist?

To push an element to an array if it doesn't exist, use the indexOf() method to check if the value is present in the array. The indexOf method returns -1 if the value is not contained in the array, in which case we should use the push() method to add it.


3 Answers

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 } 
like image 72
metadept Avatar answered Oct 31 '22 05:10

metadept


jsFiddle Demo

Use hasOwnProperty like this:

var a = []; if( a.hasOwnProperty("index") ){  /* do something */   } 
like image 45
Travis J Avatar answered Oct 31 '22 05:10

Travis J


You can also use the findindex method :

var someArray = [];

if( someArray.findIndex(x => x === "index") >= 0) {
    // foud someArray element equals to "index"
}
like image 29
abahet Avatar answered Oct 31 '22 05:10

abahet