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.
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.
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.
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.
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 }
jsFiddle Demo
Use hasOwnProperty
like this:
var a = []; if( a.hasOwnProperty("index") ){ /* do something */ }
You can also use the findindex method :
var someArray = [];
if( someArray.findIndex(x => x === "index") >= 0) {
// foud someArray element equals to "index"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With