admin管理员组

文章数量:1323715

if(Condition) {

} 

if(condition) {

}

if(condition) { 

} else { 

}

If the first condition fails, it should break instead of executing the last if/else conditon

if(Condition) {

} 

if(condition) {

}

if(condition) { 

} else { 

}

If the first condition fails, it should break instead of executing the last if/else conditon

Share Improve this question asked Jun 21, 2011 at 10:41 John CooperJohn Cooper 7,65133 gold badges83 silver badges102 bronze badges 1
  • Have you tried a switch-case scenario? – user557419 Commented Jun 21, 2011 at 10:45
Add a ment  | 

5 Answers 5

Reset to default 2
if (condition1) { 
   if (condition2) {
   }

   if (condition3) {
   }
   else {
   }
}

Or am I missing something?

What type are we working with here? What is Condition?

If you have more than 2 possible values for Condition I remend that you use Switch - Case

switch (Condition)
{
    case 'Case1' :
        // Insert logic here
        break;
    case 'Case2' :
        // Insert logic here
        break;
    case 'Case3' :
        // Insert logic here
        break;
}

Seems to me, you could just do the following:

if(Conditon) {
  // code
} else if(Condition) {
  // code
} else if(Condition) {
  // code
} else {
  // code
}

Hope it helps!

all above named solutions are functionally correct. i think the most popular is this one:

if(Conditon1) {
  // code
} else if(Condition2) {
  // code
} else if(Condition3) {
  // code
} else {
  // code
}

If you ask some Design-Pattern and Refactoring fans, you will maybe get this one:

if(Conditon1) {
  return doSomething();
} 

if(Condition2) {
  return doSomething2();
} 

if(Condition3) {
  return doSomething3();
}

it depends on your programming-style and what kind of books you've read :)

Erm, use nested if statements? I'm not entirely sure what you want to do with the result of the second condition, but here's what it looks like if the first condition isn't met:

if (condition1) {
  // First condition succeeds

  // Assuming you want to execute this either way
  if (condition2) {
  }

  // Only execute if first condition succeeds
  if (condition3) {
  } else {
  }
} else {
  // First condition fails

  // Assuming you want to execute this either way; ignore otherwise
  if (condition2) {
  }
}

Note also that if you want to return a value from a function, you can use something like if (!condition1) return false;.

As for whether the above is what you're looking for: this question is mad ambiguous.

本文标签: javascriptIf condition breakStack Overflow