How add a personage in an array?

I have 4 arrays with several personages

var p1 = ['Tya', 21 ];
var p2 = ['Milo', 30];
var p3 = ['Lili', 15];
var persos = [p1,p2,p3];

The option 1 allows to visualize my personages

   case 1 : console.log("Option 1 - Display personage n");
            
            for(var i=0; i<persos.length; i++){
               console.log("*****************");
               console.log("Personage n° " + (i+1));
               console.log("Name : " + persos[i][0]);
               console.log("Age : " + persos[i][1]);
             }
   break;

The option 2 allows to add a personage, except that when I enter a personage. I don’t retrieve this personage in option 1 .

case 2 : console.log("Option 2 - Add personagen");
         var perso = [];
         perso.push(readline.question("Enter your name please ? "));
         perso.push(readline.questionInt("Enter your age please ? "));
         console.log("Adding personage !");                
break;

var readline = require("readline-sync");

var menu = "1/ Display personage : n";
menu += "2/ Add personage : n";
menu += "0/ Exit :n";

var choice = -1;

var p1 = ['Tya', 21 ];
var p2 = ['Milo', 30];
var p3 = ['Lili', 15];
var persos = [p1,p2,p3];



do{ 
    console.log("*********** MENU ************");
    console.log(menu);
    choice = readline.questionInt("Enter your choice please : ");

    switch(choice){

        case 1 : console.log("Option 1 - Display personage n");
            
                for(var i=0; i<persos.length; i++){
                    console.log("*****************");
                    console.log("Personage n° " + (i+1));
                    console.log("Name : " + persos[i][0]);
                    console.log("Age : " + persos[i][1]);
                }
        break;

        case 2 : console.log("Option 2 - Add personagen");
                 var perso = [];
                 perso.push(readline.question("Enter your name please ? "));
                 perso.push(readline.questionInt("Enter your age please ? "));

                 console.log("Adding personage !");                

        break;


        case 0 : console.log("Exitn");
        break;

        default : console.log("Untreated case ! n");
    }
} while(choice !== 0);

Answer

Don’t clear persos when adding a new personage. Remove the line:

var perso = [];

You have to create an array containing the name and age, and push that array once rather than pushing the name and age separately.

var name = readline.question("Enter your name please ? ");
var age = readline.questionInt("Enter your age please ? ");
perso.push([name, age])

Leave a Reply

Your email address will not be published. Required fields are marked *