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 的情况下


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01