在切换 Javascript 案例中使用字符串"includes()"



在Javascript中,有没有办法实现类似的东西?

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]; 解决了我的问题,并将开关外壳应用于type

这将起作用,但不应在实践中使用。

const databaseObjectID = "someId"; // like "product/217637"
switch(true) {
    case databaseObjectID.includes('product'): actionOnProduct(databaseObjectID); break;
    case databaseObjectID.includes('user'): actionOnUser(databaseObjectID); break;
    // .. a long list of different object types
}

您的使用将被视为滥用大小写。

相反,只需使用 ifs

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

如果 ObjectId 包含产品或用户周围的静态内容,则可以将其删除并使用用户或产品作为键:

var actions = {
  "product":actionOnProduct,
  "user"   :actionOnUser
}
actions[databaseObjectId.replace(/..../,"")](databaseObjectId);

对不起,我是一个菜鸟,所以有人可能不得不清理这个,但这是这个想法。 传递给函数以检查并返回类别,然后使用开关。

function classify(string){
  var category = categorize(string);
  switch (category) {
    case 'product':
      console.log('this is a product');
      break;
    case 'user':
      console.log('this is a user');
      break;
    default:
      console.log('category undefined');    
  }
}
function categorize(string){
  if (string.includes('product')){
    return 'product';
  }
  if (string.includes('user')){
    return 'user';
  }
}
classify("product789");
classify("user123");
classify("test567");

也很抱歉与您的示例不匹配。

问题:

在切换 JavaScript 案例中使用字符串 "include((">

虽然 includes() 方法有效,但它区分大小写,并且只匹配任何字符。 我找到了一个我更喜欢的正则表达式解决方案,并且提供了很大的灵活性。 例如,您可以轻松地将其更改为仅匹配 WORDS。

var sourceStr = 'Some Text and literaltextforcase2 and more text'
switch (true)  {  // sourceStr
  case (/LiteralTextForCase1/i.test(sourceStr)):
      console.log('Case 1');
      break;
  case (/LiteralTextForCase2/i.test(sourceStr)):
    console.log('Case 2');
    break;
  default:
      console.log('ERROR No Case provided for: ' + sourceStr);
};
//-->Case 2

最新更新