最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return false from a switch statement - Stack Overflow

programmeradmin1浏览0评论

I have a switch statement with multiple cases in JavaScript. But in one of the cases, I do not want to proceed if a condition is false.

How do I do this.

Take for eg.:

switch (case) {
    case "1":
        // some code
        break;
    case "two":
        // some code
        break;
    case "III":
        if (!shouldProceed) {
          return false;
        }
        // tasks to be done for case III
        break;
    case "4": 
        // case 4 code
        break;
    default:
        // default tasks
        break;
    }

My task 3 is a switch case, but it is conditional. Is it safe to return false from a case in the above way. What can be a better approach for this?

I have a switch statement with multiple cases in JavaScript. But in one of the cases, I do not want to proceed if a condition is false.

How do I do this.

Take for eg.:

switch (case) {
    case "1":
        // some code
        break;
    case "two":
        // some code
        break;
    case "III":
        if (!shouldProceed) {
          return false;
        }
        // tasks to be done for case III
        break;
    case "4": 
        // case 4 code
        break;
    default:
        // default tasks
        break;
    }

My task 3 is a switch case, but it is conditional. Is it safe to return false from a case in the above way. What can be a better approach for this?

Share Improve this question asked Feb 14, 2014 at 10:11 KingJulianKingJulian 9731 gold badge9 silver badges20 bronze badges 3
  • Yes you can return false, it's safe. – Denys Séguret Commented Feb 14, 2014 at 10:12
  • there's no problems with doing that – Tanner Commented Feb 14, 2014 at 10:12
  • As long as you don't have any code you still need to execute after the switch statement that should be fine. – Anthony Grist Commented Feb 14, 2014 at 10:13
Add a ment  | 

1 Answer 1

Reset to default 4

It is safe if this switch statement is contained inside a function. Just remember that it will also stop the function and return false immediately:

var foo = function (bar) {
    switch (bar) {
        case 1:
            return false;
        case 2:
            bar++;
            break;
        default:
            return true;
    }
    return bar;
};

console.log(foo(1));    // false
console.log(foo(2));    // 3
console.log(foo(3));    // true
发布评论

评论列表(0)

  1. 暂无评论