Find out if a variable is in an array?
jQuery has a utility function to find whether an element exist in array or not
$.inArray(value, array)
It returns index of the value in array
and -1
if value is not present in array. so your code can be like this
if( $.inArray(code, countryList) != -1){
alert('value is Array!');
} else {
alert('Not an array');
}
instanceof
is for checking if an object is of a certain type (which is a whole different topic). So instead of the code you wrote, you should lookup in the array. You can either check every element like this:
var found = false;
for( var i = 0; i < countryList.length; i++ ) {
if ( countryList[i] === code ) {
found = true;
break;
}
}
if ( found ) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
Or you can use the simpler method of using indexOf()
function. Every array has an indexOf()
function that loops up an element and returnns its index in the array. If it can't find the element, it returns -1. So you check the output of indexOf()
to see if it has found anything in the array that matches your string:
if (countryList.indexOf(code) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
I would use the second algorithm because it is simpler. But the first algorithm is good too because it is more readable. Both have the same income, but the second one has better performance and is shorter. However, it is not supported in older browsers (IE<9).
If you are using the JQuery library, you may use the inArray()
function which works in all browsers. It is the same as indexOf()
and retuns -1 if it doesn't find the element you are looking for. So you can use it like this:
if ( $.inArray( code, countryList ) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
You seem to be looking for the Array.indexOf function.
You need to use Array.indexOf
:
if (countryList.indexOf(code) >= 0) {
// do stuff here
}
Please not that it is not supported in and before IE8 (and possibly other legacy browsers). Find out more about it here.