Javascript - 获取切换案例中的案例数 [英] Javascript - get number of cases in switch case
问题描述
是否可以在 Javascript 中获取 switch case 语句中的 case 数?
Is it possible to get the number of cases in a switch case statement in Javascript?
所以对于这样的事情
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});
},
推荐答案
在 javascript 中 switch
和 case
是关键字逻辑操作符,没有原型或者可以通过JavaScript 引擎.但是,functions
是动态对象,因此如果将 switch 语句放在函数中,则可以在该函数上调用 toString()
来评估函数的内容,如下所示:
In javascript switch
and case
are keyword logical operators and do not have a prototype or are introspectable by the javascript engine. However, functions
are dynamic objects so if you put a switch statement within a function, then you can call toString()
on that function to evaluate the function's contents like this:
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
出现的次数.
Note: The regex is error prone, but gives you a gist of the strategy. I'll let you get fancy with the regex to find out how many times the word case
occurs.
这篇关于Javascript - 获取切换案例中的案例数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!