gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:39:52 25 4
gpt4 key购买 nike

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

最佳答案

在 javascript 中,switchcase 是关键字逻辑运算符,没有原型(prototype)或可由 javascript 引擎自省(introspection)。但是,函数 是动态对象,因此如果您将 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 出现了多少次。

关于Javascript - 获取开关案例中的案例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33364691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com