如何在 Javascript 三元运算符的输出中声明变量?

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

我正在尝试自学三元运算符,但遇到了一个问题。为了最好地解释我正在尝试做的事情,下面是我希望我的代码看起来像什么的伪代码:

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

本质上,我试图复制类似下面的 if/else 代码,但使用三元运算符(为了压缩我的代码),我似乎找不到声明 [=三元运算的第二个条件中的13=]位:

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."
    }
  }
}();

对于上下文,我正在使用 discord.js 构建一个掷骰子的 Discord Bot,这样我和我的朋友就不需要在一起在同一个地方玩桌面游戏,因此 "roll" 和 "keep" 个变量。

我认为您不能在三元语句的最后部分(: 之后)使用多行表达式——您可以尝试将其放入一个函数中并从最外层的三元语句中调用它。

您可以使用辅助函数来比较值并将拆分后的值传播到函数

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

你不能在另一个变量声明中有变量声明,除此之外,你的伪代码有效:

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)

此答案基于 . But further removes the non-required parentheses and makes use of unary plus operator 将字符串转换为整数。

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