Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何减少javascript中的if语句?_Javascript_If Statement - Fatal编程技术网

如何减少javascript中的if语句?

如何减少javascript中的if语句?,javascript,if-statement,Javascript,If Statement,我正在用普通JavaScript编写代码,但我不想编写一千个不同的if语句 我已经尝试在JavaScript中搜索如何减少if语句,但没有发现任何有用的东西 下面是一些示例代码: if (a == "text" && b == "othertext") { console.log("message"); } else if (a == "text2" && b == "othertext2") { console.log("other message");

我正在用普通JavaScript编写代码,但我不想编写一千个不同的if语句

我已经尝试在JavaScript中搜索如何减少if语句,但没有发现任何有用的东西

下面是一些示例代码:

if (a == "text" && b == "othertext") {
  console.log("message");
} else if (a == "text2" && b == "othertext2") {
  console.log("other message");
} else if (a == "text3" && b == "othertext3") {
  console.log("other other message");
} else if (a == "text4" && b == "othertext4") {
  console.log("other other other message");
} else if (a == "text5" && b == "othertext5") {
  console.log("other other other other message");
} else if (a == "text6" && b == "othertext6") {
  // .. and so on.
}

如果有人能帮助我,请使用数据驱动方法,将字符串用作对象中的键

const消息={
“文本|其他文本”:“消息”,
“文本1 |其他文本1”:“消息1”,
“文本2 |其他文本2”:“消息2”
};
功能显示信息(a、b){
让key=`${a}|${b}`;
if(messages.hasOwnProperty(键)){
日志(消息[key]);
}否则{
控制台日志(“无效的a和b”);
}
}

showMessage(“文本”、“其他文本”)我想您可以使用三元运算符

let msg = '';
msg = a === 'text' && b === 'othertext' : msg;
msg = a === 'text2' && b === 'othertext2' : msg; 
// etc.

最终,它不会变得更漂亮,但可能会更容易键入。

您匹配的内容是否有逻辑,或者它们是任意字符串?只是任意字符串如果您有100个不同的条件,您希望以不同的方式处理,您必须根据需要使用
if
switch
语句。我建议你的问题更具体、更清楚。