使用字符串“includes()”在切换Javascript的情况下 [英] use string "includes()" in switch Javascript case

查看:124
本文介绍了使用字符串“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
}

这个更多的是一个好奇的问题,以了解切换/案例的可能性,因为在这个特殊情况下,我已经使用 const type = databaseObjectID.split('/')[0]解决了我的问题; 并在上应用开关案例

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆