首页 > 解决方案 > 如何在 Javascript 三元运算符的输出中声明变量?

问题描述

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

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 代码但使用三元运算符(为了压缩我的代码),并且我似乎找不到在const三元运算的第二个条件中声明位的正确格式:

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”变量。

标签: javascriptconditional-operator

解决方案


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

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


推荐阅读