instanceof
オブジェクトが特定のタイプであるかどうかを確認するためのものです(これはまったく別のトピックです)。したがって、作成したコードの代わりに、配列を参照する必要があります。次のようにすべての要素を確認できます。
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
...
}
または、関数を使用するより簡単な方法を使用できindexOf()
ます。すべての配列にはindexOf()
、要素をループして配列内のインデックスを返す関数があります。要素が見つからない場合は、-1 を返します。したがって、の出力をチェックしてindexOf()
、文字列に一致するものが配列内に見つかったかどうかを確認します。
if (countryList.indexOf(code) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
2 番目のアルゴリズムの方が簡単なので、2 番目のアルゴリズムを使用します。しかし、最初のアルゴリズムも読みやすいので優れています。どちらも収入は同じですが、2 番目の方がパフォーマンスが高く、短くなっています。ただし、古いブラウザー (IE < 9) ではサポートされていません。
JQuery ライブラリを使用している場合はinArray()
、すべてのブラウザで動作する関数を使用できます。と同じで、indexOf()
探している要素が見つからない場合は -1 を返します。したがって、次のように使用できます。
if ( $.inArray( code, countryList ) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}