首页 > 解决方案 > 如何从获取的结果中创建新对象?

问题描述

我正在尝试使用获取的结果(一些文本)来创建一个新对象,这是我到目前为止的代码

     <script>

    class Student {
   
   constructor(name, address, phone, course) {
    this.name = name;
    this.address = address;
    this.phone = phone;
    this.course = course;
   }
   getInfo() {
        return "Ime: " + this.name + "\n" +
"Adresa: " + this.address + "\n" +
"Telefon: " + this.phone + "\n" +
"Kurs: " + this.course;
    }  }
    
   

  async function getData () {
      const response = await fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt');
      const students = await response.text();
      
      return students;
  }

  document.addEventListener("DOMContentLoaded" , async ()=>{

 

   try {
       students = await getData();
   }catch(e) {
       console.log("Error!");
       console.log(e);
   }

   

console.log(students);


  })


    </script>
> *Fetch text is something like this:*
>     Ebonie 
>     7175 Muland Street
>     8343242
>     Math
>     Keenan 
>     2 Elm Lane
>     832432
>     History***
As a result i need to get:
var student1 = new Student(" Ebonie "," 7175 Muland Street",8343242,"Math");
var student2 = new Student("  Keenan  ","  2 Elm Lane",832432, History");
......

我想我需要遍历文本,然后以某种方式将文本存储到新对象中。
输出应该是: 姓名:Ebonie 地址:7175 Muland Street 电话:8343242 课程:数学

标签: javascriptclassconstructorfetch

解决方案


 class Student {

   constructor(name, address, phone, course) {
     this.name = name;
     this.address = address;
     this.phone = phone;
     this.course = course;
   }
   getInfo() {
     return "Ime: " + this.name + "\n" +
       "Adresa: " + this.address + "\n" +
       "Telefon: " + this.phone + "\n" +
       "Kurs: " + this.course;
   }
 };

 var text = `
Ebonie 
7175 Muland Street
8343242
Math
Keenan 
2 Elm Lane
832432
History
`;

 var lines = text.trim().split('\n');
 var students = Array.from({
   length: lines.length / 4
 }, (_, i) => i).map(index => index * 4).map(index => new Student(lines[index], lines[index + 1], lines[index + 2], lines[index + 3]));
 
 students.forEach(element => console.log(element.getInfo()));


推荐阅读