如何循环从控制台获取输入?
让我们假设节点promt询问班上有多少学生? 在该用户输入5后,应该提示5次“一个一个地输入他们的名字”, 并且所有名称都必须存储在数组中
答案 0 :(得分:1)
您可以使用readline-sync软件包
var readline = require('readline-sync');
let num = readline.question("how many students are in a class ?");
let names=[];
for(let i=0;i<=num;i++)
{
let name = readline.question("Enter Name?");
names.push(name);
}
console.log(names);
答案 1 :(得分:1)
尝试一下
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let n;
let array = []
function mainfunction() {
if( n == array.length){
console.log("your output: ", array)
rl.close()
}
else{
rl.question('enter student name one by one \n', (name) => {
array.push(name)
mainfunction()
})
}
}
rl.question('enter the number of students ', (answer) => {
n = answer
mainfunction()
});