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
...
}