简体   繁体   中英

how to reduce if statements in javascript?

I'm writing code in vanilla JavaScript but I don't want to write a thousand different if statements.

I already tried searching up how to reduce if statements in JavaScript, but I didn't find anything helpful.

Here is some example code:

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.
}

If anyone can help me, it would be appreciated

You can use a data-driven approach by using the strings as keys in an object.

 const messages = { "text|othertext": "message", "text1|othertext1": "message1", "text2|othertext2": "message2" }; function showMessage(a, b) { let key = `${a}|${b}`; if (messages.hasOwnProperty(key)) { console.log(messages[key]); } else { console.log("Invalid a and b"); } } showMessage("text", "othertext");

You could use ternary operators I suppose.

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

Ultimately its not gonna get much prettier but that might be a little bit simpler to type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM