gpt4 book ai didi

javascript - 使用 Javascript 在 forEach 中进行切换是不好的做法吗?

转载 作者:行者123 更新时间:2023-11-30 08:00:49 26 4
gpt4 key购买 nike

使用 Javascript 在 forEach 中设置一个开关是不好的做法吗?

book.forEach(function (getBook, i) {
switch (getBook) {
case path:
string = 'some html';
break;
};
});

我的理解是,这将为 getBook 的每个实例创建一个开关。假设有 100 个。然后我有 100 个独立的开关。那很糟糕吗?

最重要的是,有没有人有更好的方法来做到这一点?似乎只有一个开关比一大堆开关更好。

最佳答案

在此示例中,调整您当前的代码,您可以执行类似 -

bookActions = {}; 

bookActions['path'] = function() { // or the real way you're loading these
// other code to generate that you would have had in
// the switch case
return 'some html';
};

然后,一旦您像以前一样拥有 100 个左右的案例,您就可以

book.forEach(function(getBook, i) { 
if (bookActions[getBook]) {
string = bookActions[getBook]();
}
});

通过这种方式,我使用文字对象作为字符串(您的代码中的 getBook)和函数(switch case 的主体)之间的映射。

关于javascript - 使用 Javascript 在 forEach 中进行切换是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28734393/

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