Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array index exists or not in javascript?

I am working with Titanium, my code looks like this:

var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{   
    return false;
}

I am passing an index to the currentData array. I still can't detect a non-existing index using the above code.

like image 321
Pradeep Avatar asked Oct 18 '22 12:10

Pradeep


People also ask

How do you check if an index of an array exists?

To check if an array index exists, access the array at the specific index and check if the result is not equal to undefined . If the result is not equal to undefined the array index exists.

How do you check if a value does not exist in an array JavaScript?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.

How do you check if an index in an array is empty JavaScript?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.


1 Answers

Use typeof arrayName[index] === 'undefined'

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
like image 503
techfoobar Avatar answered Oct 21 '22 00:10

techfoobar