use string quot;includes()quot; in switch Javascript case(使用字符串“includes();在切换 Javascript 的情况下)
问题描述
在Javascript中,有没有办法实现类似的东西?
In Javascript, is there a way to achieve something similar to this ?
const databaseObjectID = "someId"; // like "product/217637"
switch(databaseObjectID) {
case includes('product'): actionOnProduct(databaseObjectID); break;
case includes('user'): actionOnUser(databaseObjectID); break;
// .. a long list of different object types
}
这更像是一个好奇的问题,以了解 switch/case 的可能性,因为在这种特殊情况下,我使用 const type = databaseObjectID.split('/')[0]; 解决了我的问题;
并在 type
This is more a curiosity question to understand the possibilities of switch / case, as in this particular case I have solved my problem using const type = databaseObjectID.split('/')[0];
and apply the switch case on type
推荐答案
您的使用将被视为滥用案例.
You usage would be considered an abuse of case.
而只是使用 ifs
if (databaseObjectId.includes('product')) actionOnProduct(databaseObjectID);
else if (databaseObjectId.includes('user')) actionOnUser(databaseObjectID);
// .. a long list of different object types
如果 ObjectId 包含产品或用户周围的静态内容,您可以将其移除并使用用户或产品作为键:
If the ObjectId contains static content around the product or user, you can remove it and use the user or product as a key:
var actions = {
"product":actionOnProduct,
"user" :actionOnUser
}
actions[databaseObjectId.replace(/..../,"")](databaseObjectId);
这篇关于使用字符串“includes()";在切换 Javascript 的情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用字符串“includes()";在切换 Javascript 的情况下


基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01