我有一个不和谐的机器人,我正在尝试找出一种方法来知道一条消息是否是一个数字。下面是我的代码:
if (message.isNumber()){
//do something
}String.prototype.isNumber = function() {
return /^\d+$/.test(this);
};当我测试它时,它什么也不做。有人能帮帮我吗?
发布于 2021-01-06 02:34:43
您可以简单地这样做:
if(isNaN(message.content) return;
else {
//do something
}如果消息不是数字,则不会执行任何操作。否则它会做你想让它做的事情。
发布于 2021-01-06 02:36:08
由于OP没有提供更多关于message是什么的上下文,我假设message已经包含了需要检查的值。因此,我还必须忽略message可能是来自Discord.js的对象,以及OP要检查的值实际上位于message.content,而不是message。即使我知道Discord.js应用程序接口,message在这里也可能是完全不同的东西。
如果需要检查的值确实位于message.content,并且确实来自Discord.js接口,那么他可能知道更多关于Discord.js接口的信息和关于这个问题的上下文。
案例A:需要检查变量的类型是否为数字
您可以使用typeof检查它的类型:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
if (typeof message == 'number') { console.log('is a number'); }
if (!(typeof message == 'number')) { console.log('is a not a number'); }案例B:如果变量是有效数字,则需要检查该变量
在某些情况下,您可以使用isNaN。这里的字符串也可以是一个有效的数字:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
isNaN(123) // false, it is a number
isNaN('123') // false, it is a number
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true, it is not a number
isNaN('10px') // true, is is not a number你还会在这里找到一个非常好的和完整的答案:(Built-in) way in JavaScript to check if a string is a valid number
https://stackoverflow.com/questions/65584593
复制相似问题