Is there an easier to write an if statement with more than 10 conditions?
Here is my code:
if (state == 'AZ' || state == 'CO' || state == 'DC' |开发者_如何学C| state == 'IA' || state == 'LA' || state == 'MN' || state == 'NC' || state == 'ND' || state == 'NM' || state == 'NV' || state == 'OR' || state == 'SC' || state == 'TN' || state == 'VA' || state == 'WA' || state == 'WI' || state == 'WY') {}
Is there an easier way to write this using an array? This works, but I want it to be cleaner!
You can use an object:
if ({AZ:1,CO:1,DC:1,IA:1,LA:1,MN:1,NC:1,ND:1,NM:1,NV:1,OR:1,SC:1,TN:1,VA:1,WA:1,WI:1,WY:1}[state] == 1) {
Edit:
You could also look for the string in a string:
if ("AZ,CO,DC,IA,LA,MN,NC,ND,NM,NV,OR,SC,TN,VA,WA,WI,WY".indexOf(state) != -1) {
(This of course assumes that the variable contains something reasonable, a value like ","
would give a false positive.)
This happens to be even faster than the plain comparisons in most browsers: http://jsperf.com/test-regexp-vs-obj/3
Regular Expression:
if(state.match(/^(AZ|CO|DC|IA|LA|MN|NC|ND|NM|NV|OR|SC|TN|VA|WA|WI|WY)$/)){
//do whatever
}
If you're using jQuery:
var states = ['AZ' ,'CO' ,'DC' ,'IA' ,'LA' ,'MN' ,'NC' ,'ND' ,'NM' ,'NV' ,'OR' ,'SC' ,'TN' ,'VA' ,'WA' ,'WI' ,'WY'];
if($.inArray('AZ',states)>=0){
console.log('Hurrah');
}
If you're not you'll need your own function like the top answer to this question.
Push all your possibilities into an array and use indexOf to check is contained in.
Example:
if(['NA', 'NB', 'NC'].indexOf(state) > -1)
{
// true
}
Or add contains and use it :
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
if(['NA', 'NB', 'NC'].contains(state))
{
// true
}
Hava at look at this javascript version of a contains function. Simply populate an array with your state codes and check using the function
http://css-tricks.com/snippets/javascript/javascript-array-contains/
if ( ['AZ', 'CO', 'DC', 'And so on'].indexOf(state) != -1 ) {
// do something
}
NOTE: indexOf
is not supported in IE < 9. If you have to support those browsers, you can either use jQuery:
if ( $.inArray(state, 'AZ', 'CO', 'DC', 'And so on') != -1 ) {
// do something
}
or manually extend the array prototype.
var states=new Array("AZ", "CO", ...);
for (s in states) {
if (state == s) {
// do something
break;
}
}
is one way to approach it.
If you use CoffeeScript, which generates JavaScript output, you can simply write
if state in ['AZ', 'CO', 'DC', 'IA', 'LA', 'MN', 'NC', 'ND', 'NM', 'NV', 'OR', 'SC', 'TN', 'VA', 'WA', 'WI', 'WY']
...
精彩评论