我正在尝试在 node.js 中构建一个简单的计算器,它也应该验证输入。下面是下面的代码
process.stdout.write('A simple calculator created using node.js \n');
var inputs = ['Please enter your first number','Please enter the second number','Please enter the operator'];
var output1 = [];
function ask(i) {
process.stdout.write(`${inputs[i]}`);
process.stdout.write(" : ");
}
ask(0);
process.stdin.on('data',(data)=> {
if(typeof data != "number"){
console.log(ask(0));
} else {
output1.push(data);
console.log('The given input is ' + output1);
}
}
);
如果我的输入不是数字,我希望控制台循环回到函数ask()。下面应该是理想的输出
输出: 请输入您的第一个号码:p 请输入您的第一个数字:1 给定输入为 1
我知道我的代码存在一些缺陷,但不知道如何纠正它。请帮忙。
最佳答案
对 process.stdin.on
的回调将接收 Buffer
对象作为参数。
process.stdin.on('data', data => {
/** data will be buffer. */
});
您需要使用 toString()
方法将 Buffer
转换为 String
。获得 String
后,您可以尝试使用 Number
类 ( Number.parseInt
) 的方法将字符串解析为数字(Int 或 Float) > 或 Number.parseFloat
)。然后,您可以使用 Number.isNaN
方法检查解析的数字是否有效。
代码如下:
process.stdin.on('data', data => {
var string = data.toString();
var number = Number.parseFloat(string);
if (Number.isNaN(number)) {
ask(0);
} else {
output1.push(number);
console.log('The given input is ' + output1);
}
});
为了给您有关如何完成整个计算器的提示,我将创建一个 indexOfInput
并将其维护在输入上:
var indexOfInput = 0;
ask(indexOfInput);
process.stdin.on('data', data => {
var string = data.toString();
var number = Number.parseFloat(string);
if (Number.isNaN(number)) {
ask(indexOfInput);
} else {
output1.push(number);
console.log('The given input is ' + output1);
// Current input taken successfully. Let's take the next input
indexOfInput++;
ask(indexOfInput);
}
});
您将需要进一步添加 make 调整以使其完全正常工作。您的代码中的某处将需要类似的东西。
if (indexOfInput <= 1) {
/** expecting number */
} else if (indexOfInput === 2) {
/** expecting an operator */
} else {
/** all the inputs taken. process the inputs array */
}
希望这有帮助! :)
关于javascript - 如何验证 Node js 中的数字输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52454118/