use string “includes()” in switch Javascript case

前端 未结 4 692
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 06:45

In Javascript, is there a way to achieve something similar to this ?

const databaseObjectID = \"someId\"; // like \"product/217637\"

switch(databaseObjectID         


        
4条回答
  •  误落风尘
    2021-01-02 07:11

    You usage would be considered an abuse of case.

    Instead just use ifs

         if (databaseObjectId.includes('product')) actionOnProduct(databaseObjectID); 
    else if (databaseObjectId.includes('user'))    actionOnUser(databaseObjectID); 
    // .. a long list of different object types
    

    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);
    

提交回复
热议问题