Receive array values from the console

Asked

Viewed 185 times

1

I am starting the studies in Ode and decided to do an exercise in which I need to receive a value n by the Node console that will be the amount of elements of an array and receive n elements by the Node console. The problem is that I don’t know how to receive array elements from the console The code I have so far:

var readline = require('readline');
var valor = 0;
var valor1 = 0;
var conj = [];

var leitor = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

leitor.question("Digite a quantidade de itens do conjunto: ", 
function(resp,vet){
    valor = resp;
    for(var i = 0; i<valor; i++){
        console.log("Digite o valor de indice "+i);
        valor1 = vet;
        conj.push(valor1);
    }
    console.log(conj);
    leitor.close();
});
  • Carlos, lacked you describe your problem or doubt!

  • i don’t know how to receive the elements of an array through the Node console, I can only receive 1 number

1 answer

3


There are some minor problems in your code.

First: The function callback of the reader method.() receives only one argument, which is the string the user has typed. I mean, it would look like this:

leitor.question("Digite a quantidade de itens do conjunto: ", function(resp){

This leads us to another problem: Inside the for, we would have to ask to enter a value for each index, right? I mean:

for(var i = 0; i < resp; i++){
    leitor.question('Digite o valor de indice ' + i, (valor) => {
        conj.push(valor); 
    });
}

The problem is that the for does not wait for the user to type and the reader method.Question() is completed. So in a case where I want a set with only three elements, it would happen this:

> Digite a quantidade de itens do conjunto: 3
> Digite o valor de indice 0Digite o valor de indice 0Digite o valor de indice 0[]

Got it?
One way to solve this is with a asynchronous function. I gave some other improvements to your code, but it would look something like this:

const readline = require('readline');
const leitor = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const conj = [];

leitor.question('Digite a quantidade de itens do conjunto: ', async (quantidade) => {
    for(let i = 0; i < quantidade; i++) {
        // O await espera pelo retorno da Promise
        await new Promise((resolve) => { 
            leitor.question(`Digite o valor de indice ${i}: `, (valor) => {
                resolve(conj.push(valor)); // A promise resolve e retorna
            });
        });
    }
    leitor.close();
    console.log(conj);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.