Search code examples
javascriptarraysclasspromptconsole.log

How to save the data of an array by prompts and bond with a class in javascript


The data that is saved in an array through prompts as I do to link it with a class and display it with a method (console.log (information ())

class Libro {

   constructor(titulo, autor, año, genero) {

      this.titulo = titulo
      this.Autor = autor
      this.Año = año
      this.Genero = genero
   }

   informacion() {
      return console.log(`El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`);
   }
}

let titulo1 = prompt('Introduce el titulo del libro')
let autor1 = prompt('Introduce el autor del libro')
let año1 = prompt('Introduce el año en que fue publicado el libro')
let genero1 = prompt('Introduce el genero literario del libro')

let libro1 = [titulo1, autor1, año1, genero1];

libro1.push(new Libro(titulo, autor, año, genero))

console.log(libro1.informacion());

Solution

  • Class identifiers refer to the class constructor function.

    Replace

    let libro1 = [titulo1, autor1, año1, genero1];
    
    libro1.push(new Libro(titulo, autor, año, genero))
    
    console.log(libro1.Libro());
    

    with

    let libro1 = new Libro(titulo, autor, año, genero)
    libro1.informacion()   // call the informacion method of libro1
    

    which creates a class instance object, assigns it to libro1, and then calls the informacion method of libro1.

    If you want an array of book objects, you could save libro1 (and other books) in an array:

    const libri = [];
    ...  // create libro1
    libri.push(libro1);
    ...  // create libro2
    libri.push( libro2);
    

    To create more than one book, try putting the prompts inside a function that returns a Libro class object. That way all books use the same set of prompts.


    In response to comment, the informacion method already calls console.log and returns undefined if that is what console.log returns. Returning an information string may better suit your purpose:

    informacion() {
          return `El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`;
       }
    

    If the result of the prompts is saved in an array, like

    let arr = [titulo, Autor, Año, Genaro];
    

    you can pass them to the constuctor function using rest parameter syntax:

    let libro = new Libro( ...arr );