【问题标题】:How to prevent float and negative input using Javascript?如何使用 Javascript 防止浮动和负输入?
【发布时间】:2021-04-17 08:49:20
【问题描述】:

我正在使用 readlineSync.questionInt,如果用户键入浮点数或负数,我需要提示消息。我使用了一个限制,但这还不够。

var readlineSync = require('readline-sync');
var number_of_people = readlineSync.questionInt('How many people are you going with?', { limit: 0 - 9 });

【问题讨论】:

    标签: javascript node.js input numbers


    【解决方案1】:

    我将只使用 question 并将您的自定义登录移动到 limit 回调中。例如,一个想法可能是检查输入是否为整数并且在0-9 之间的范围内:

    var readlineSync = require('readline-sync');
    var number_of_people = readlineSync.question('How many people are you going with?', {
      limit: function(i) {
        const input = Number(i);
        return  Number.isInteger(input) && input > 0 && input < 10;
    }});
    

    你也可以使用正则表达式;当输入根据您的逻辑有效时,只需让您的回调返回true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多