Javascript-获取开关案例中的案例数

超级堆栈

是否可以在Javascript的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});
    },
cosbor11

在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

注意:regex容易出错,但是可以让您大致了解该策略。我会让您喜欢正则表达式以找出单词case出现了多少次

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章