Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

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());
question from:https://stackoverflow.com/questions/65866263/how-to-save-the-data-of-an-array-by-prompts-and-bond-with-a-class-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...