javascript - 如何在 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”变量。
解决方案
您可以使用辅助函数来比较值并将拆分的值传播到函数
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 - JSON.parse() 不适用于可变类型字符串,但如果直接使用,它可以处理其内容
- mysql - 仅当字段已填写时才计数
- android - 如何创建仅更改为一项活动的图像视图?
- gnuplot - Gnuplot 自动关闭
- lua - 重新定义后如何恢复/调用原始函数?
- spring - 春季无法从数据库单元测试中删除行
- python - 显示单元格的开始和结束
- php - 为什么我引导 PHP 时 imap.so PHP 扩展会进行网络调用?
- jhipster - 是否可以在不覆盖自定义代码的情况下更新 jhipster 实体
- python - 给定类别 0、1、2 的 y_pred,我如何仅选择类别 1 和 2 来在 Keras 中执行指标?