How to take input from console in a loop ?
Let us suppose node promt asks how many students are in a class? after this user enter 5, then there should be a promt asking 5 times "enter their name one by one", and all name has to be stored in an array
You can do something like this with the readline-sync package
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);
Working repl- https://repl.it/repls/LightyellowEvenBusinesses
Try this
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()
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.