簡體   English   中英

Discord.js 檢查消息是否為數字

[英]Discord.js check if message is a number

我有一個 discord 機器人,我正在嘗試找出一種方法來了解消息是否為數字。 這是我的代碼:

if (message.isNumber()){
   //do something
}
String.prototype.isNumber = function() {
  return /^\d+$/.test(this);
};

當我測試它時,它完全沒有任何作用。 有人可以幫我嗎?

你可以簡單地做:

if(isNaN(message.content) return;
else {
  //do something
}

如果消息不是數字,它什么也不做。 否則它會做你想做的事。

由於 OP 沒有提供有關message是什么的更多上下文,因此我假設message已經包含需要檢查的值。 因此,我還必須忽略該message可能是來自 Discord.js 的 object,並且 OP 要檢查的值確實位於message.content ,而不是message 即使我知道 Discord.js API,這里的message也可能完全不同。

If the value that needs to be checked really is located at message.content and does come from Discord.js API, checkout @JannikSchmidtke answer, he might know more about the Discord.js API and the context about this question.


案例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 檢查字符串是否為有效數字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM