如何在Javascript三元运算符的输出中声明变量?
我正试图自学三元运算符,却被困在一个问题上。为了更好地解释我正在尝试做什么,下面是我希望代码看起来像什么的伪代码:如何在Javascript三元运算符的输出中声明变量?,javascript,conditional-operator,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); (parse
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 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机器人,这样我和我的朋友就不必在同一个地方玩桌面游戏,因此就有了“roll”和“keep”变量。我认为在三元语句的最后一部分不能有多行表达式(在
之后:
)--您可以尝试将其放入一个函数中,并从最外层的三元调用它。您可以使用一个helper函数来比较值,并将分割的值分散到函数中
const
正则表达式=/\d+k\d+/,,
输入=“8k4”,
比较=(a,b)=>+a>=+b,
答复=!正则表达式测试(输入)
? “正则表达式不匹配。”
:比较(…input.split('k'))
? “格式正确!”
:“保持比滚动更重要。”;
控制台日志(响应)代码>您不能在另一个变量声明中包含变量声明,除此之外,您的伪代码可以工作:
const regex=/\d+k\d+/;
常量输入=“8k4”;
常量响应=(!regex.test(输入)?“regex不匹配。”:(
parseInt(input.substring(0))>=parseInt(input.substring(2))?
“格式正确!”:“保持大于滚动。”)
)
console.log(response)
这个答案是在。但进一步删除了不需要的括号,并使用将字符串转换为整数
const response = regex.test(input)
? +input.substring(0) >= +input.substring(2) ? 'Correct Format!' : 'Keep is greater than Roll.'
: 'Regex does not match.'
顺便说一句,子字符串(2)
不适用于例如12k20
这是一个很好的观点。哎呀。