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

标签 javascript conditional-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 代码的内容,但使用三元运算符(为了压缩我的代码),并且我似乎找不到声明 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 机器人,这样我和我的 friend 就不需要在一起在同一个地方玩桌面游戏,因此有“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);

关于javascript - 如何在 Javascript 三元运算符的输出中声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238786/

相关文章:

javascript - 如何在响应式背景中创建对 Angular 线

c# - 条件运算符使用错误

c# - 条件运算符?

javascript - IF、OR 和 AND 以及不同的结果 JavaScript

带有 void 操作数的 C++ 条件运算符

javascript - 对象方法函数: Anonymous or named?

javascript - 在expo react-native中打开键盘时如何隐藏TabBar

php - jQuery IE。 ajax请求只运行一次

javascript - RxJs:为某些值延迟 onNext?

swift - 协议(protocol)一致性检查