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