javascript - 如何从获取的结果中创建新对象?
问题描述
我正在尝试使用获取的结果(一些文本)来创建一个新对象,这是我到目前为止的代码
<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 课程:数学
解决方案
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()));
推荐阅读
- mysql - 如何使用单个 sql 请求向 mysql 表中插入一些行
- visual-studio - 如何使用回车键更改选项卡以进行自动完成?
- jquery - 找出列表中有多少组 3
- javascript - 使用 Caporal npm javascript 的总和(无限参数)
- swift4 - 我正在尝试在 swift 4 的配置文件中获取特定的登录用户数据
- c++ - 空白(); 带空括号的无效
- json - JSON 模型建议
- c - 我的代码给了我一个分段错误,我做错了什么?
- java - JUnit 测试 ArrayList 元素不重复
- android - 如何修复错误:找不到符号方法 getSharedPreferences(Switch,int)