如何在 JavaScript 中使用 readline() 从用户在终端中的输入中填充数组?(无网络)



来自用户在终端中给出一些值的程序,然后我处理这些信息,如:

const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("number 1: ", function(one) {
rl.question("number 2: ", function(two) {
rl.question("number 3: ", function(three) {
if (one > two && one > three) {
console.log("bigger: " + one);
} else if (two > one && two > three) {
console.log("bigger: " + two);
} else {
console.log("bigger: " + three);
}
rl.close();
});
});
});
rl.on("close", function() {
console.log("nBYE BYE !!!");
process.exit(0);
});

我想做一些类似的事情:使用readline()从终端获取用户输入并填充数组[10],类似于:

const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var vector = new Array(10);

for (i = 0; i < vector.length; i++) {
rl.question("value " + (i+1) + ": ", function(one) {
temp = parseInt(one);
vector.splice(i, 0, temp);
});
if (i = vector.length) {
rl.close();
};
};
rl.on("close", function() {
var biggest = Math.max.apply(null, vector);
var smallest = Math.min.apply(null, vector);
console.log("biggest " + biggest + " and smallest " + smallest);
process.exit(0);
});

提示吗?

.question()基本上是异步的。它被赋予一个回调(在未来某个未知的时间执行)并立即返回。所以你剩下的代码就不用等待了。

一种可能的处理方法:

const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const vector = new Array(10);
const handleResults = function(index, vector, answer) {
// process the answer
vector[index] = parseInt(answer);
// start the next question
index++;
if(index < vector.length) {
// ask next question
rl.question("value " + index + ": ", handleResults.bind(this, index, vector));
}
else {
// we're done, wrap things up
rl.close();
}
};
rl.on("close", function() {
var biggest = Math.max.apply(null, vector);
var smallest = Math.min.apply(null, vector);
console.log("biggest " + biggest + " and smallest " + smallest);
process.exit(0);
});
// Start the questions
rl.question("value 0: ", handleResults.bind(this, 0, vector));

另一个(可能更好的)选择是使用承诺。然而,我将把这个问题留给另一个答案。

最新更新