简体   繁体   中英

How do I declare a variable in the output of a Javascript ternary operator?

I am trying to teach myself about Ternary Operators, and am stuck on a problem. To best explain what I am trying to do, below is pseudocode of what I want my code to look like:

const regex = /\d+k\d+/;
const input = "8k4";

const response = (!regex.test(input) ? "Regex does not match." : (
  const roll = input.substring(0);
  const keep = input.substring(2);
  (parseInt(roll) >= parseInt(keep) ? "Correct Format!" : "Keep is greater than Roll." )
);

console.log(response);

In essence, I am trying to replicate something like the following if/else code but using ternary operators (in order to condense my code), and I cannot seem to find the correct format for declaring the const bits in the second condition of the ternary operation:

const response = function() {
    if(!regex.test(input)) {
    return "Regex does not match.";
  } else {
    const roll = input.substring(0);
    const keep = input.substring(2);
    if(parseInt(roll) >= parseInt(keep)) {
      return "Correct Format!";
    } else {
      return "Keep is greater than Roll."
    }
  }
}();

For context, I am building a dice-rolling Discord Bot using discord.js so my friends and I don't need to be together to play tabletop games in the same place, hence the "roll" and "keep" variables.

You could use a helper function for comparing values and spread the splitted values to the function

 const regex = /\\d+k\\d+/, input = "8k4", compare = (a, b) => +a >= +b, response = !regex.test(input) ? "Regex does not match." : compare(...input.split('k')) ? "Correct Format!" : "Keep is greater than Roll."; console.log(response); 

You can't have variable declarations inside of another variable declaration, other than that, your pseudocode works:

 const regex = /\\d+k\\d+/; const input = "8k4"; const response = (!regex.test(input) ? "Regex does not match." : ( parseInt(input.substring(0)) >= parseInt(input.substring(2)) ? "Correct Format!" : "Keep is greater than Roll." ) ) console.log(response) 

我认为您在三元声明的最后部分(在:之后)不能有多行表达式-您可以尝试将其放入函数中并从最外面的三元调用。

This answer develops on Luca's answer above . But further removes the non-required parentheses and makes use of unary plus operator to convert string to integer.

const response = regex.test(input)
? +input.substring(0) >= +input.substring(2) ? 'Correct Format!' : 'Keep is greater than Roll.'
: 'Regex does not match.'

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