Javascript - 获取 switch case 中的 case 数量

Javascript - get number of cases in switch case

是否可以在Javascript中获取switch case语句中的case数?

所以对于这样的事情

showError: function (status) {
        var message = '';

        //If the error comes from the browser's routing sys (the event parameter is the failed route), default to a 404 error
        if (typeof status === 'string') {
            status = 404;
        }

        //Determines the appropriate error message
        switch (status) {
            case 404:
                message = 'the page could not be found'; 
                break;

            case 500:
                message = 'internal server error';
                break; 
        }

        //Renders the view-less error template
        region.show(new Backbone.View());
        region.el.innerHTML = Marionette.TemplateCache.get(TemplIds.error)({message: message});
    },

如果您需要知道有多少案例,为什么不将案例替换为:

case_tot_nr=0
if ()
{ ... }
case_tot_nr++;
if()
{ ... }
case_tot_nr++;
if()
{ ... }
case_tot_nr++;
...

我想不出这有什么用,反正恕我直言,你的问题很奇怪。

在 javascript 中,switchcase 是关键字逻辑运算符,没有原型或可由 javascript 引擎自省。但是,functions 是动态对象,因此如果您在函数中放置 switch 语句,则可以对该函数调用 toString() 来计算函数的内容,如下所示:

var fn = function(value){
  switch(value){
    case "A": 
      return "Apple";
    case "B":
      return "Banana";
  }
};

var fnToString = fn.toString();
var fnBody = fnToString.match(/function[^{]+\{([\s\S]*)\}$/)[1];
var count = fnBody.match(/case/g).length; //should equal 2

注意:正则表达式容易出错,但为您提供了策略的要点。我会让你看中正则表达式,找出单词 case 出现了多少次。

是的,您可以通过暴力破解来做到这一点:提供具有所有可能值的函数并分析变化。并非所有更改都可以检测到,但如果您知道来源并可以对其进行编辑 - 调整“大小写”来帮助您是微不足道的。