You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js strike系统数字范围校验if语句被忽略失效问题

Strike记过系统入参范围校验失效修复方案

问题现象

开发最高支持3次记过的违规管理系统时,需要校验入参strikeNumber取值范围为1~3,但对应if判断始终不触发,控制台无报错,核心问题代码如下:

let strikeNumber = args[2] //(Args 0 is the command it self, Args 1 is the user, Args 2 is the `Strikenumber`, and Args 3 is the reason.)

if (!strikeNumber) {
    return message.reply("Please state the number of the strike. (Example: 1, 2, 3)")
} if (!strikeNumber > 0 && !strikeNumber < 4) {
    return message.reply("Strike number must be from 1 to 3.")
}

故障原因

代码存在3个直接导致逻辑失效的问题:

  • 运算符优先级错误:逻辑非!优先级高于比较运算符,!strikeNumber > 0会先对strikeNumber取反得到布尔值,再转数字参与比较。非空字符串取反结果为false,转数字等于0,0 > 0永远为false,整个条件永远无法满足
  • 逻辑判断错误:校验1~3的合法区间,非法场景是数值小于1 或者 大于3,原代码用&&要求两个条件同时成立才触发,逻辑本身不成立
  • 类型缺失转换:从消息参数中取到的args[2]默认是字符串类型,直接参与数值比较存在隐式转换风险,边界场景容易出异常

修复代码

// 先将入参转为10进制整数
let strikeNumber = parseInt(args[2], 10); 
//(Args 0 is the command it self, Args 1 is the user, Args 2 is the `Strikenumber`, and Args 3 is the reason.)

if (!strikeNumber) {
    return message.reply("Please state the number of the strike. (Example: 1, 2, 3)")
}
// 正确拦截不在1~3区间的非法值
if (strikeNumber < 1 || strikeNumber > 3) {
    return message.reply("Strike number must be from 1 to 3.")
}

优化建议

如果需要更严谨的校验,可增加非数字判断,拦截用户传入字母、特殊字符等非法输入:

if (isNaN(strikeNumber) || strikeNumber < 1 || strikeNumber > 3) {
    return message.reply("Strike number must be a valid integer from 1 to 3.")
}

内容的提问来源于stack exchange,提问作者Hamoodi youtube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 01:18:21