在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 的情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!