【发布时间】:2020-05-24 04:31:33
【问题描述】:
大家好!我创建了以下代码并想知道如何修复代码,以便当我添加同一个学生时,if 语句可以正常运行。非常感谢您的帮助
class Student {
constructor(name, email, community) {
this.name = name;
this.email = email;
this.community = community;
}
}
class Bootcamp {
constructor(name, level, students = []) {
this.name = name;
this.level = level;
this.students = students;
}
registerStudent(studentToRegister) {
if (this.students.forEach(s => s.email === s.email)) {
console.log(`The student ${studentToRegister.email} is already registered!`);
} else {
this.students.push(studentToRegister);
console.log(`Registering ${studentToRegister.email} to the bootcamp ${this.name}.`);
}
return this.students;
}
}
// For testing
// Creating new Bootcamp
const webDevFund = new Bootcamp("Web Dev Fundamental", "Biginner");
const fullStack = new Bootcamp("Full Stack Web Dev", "Advance");
// Adding new Bootcamp
const Max = new Student("Max", "max@fyard.net", "PAP");
const Bird = new Student("Bird", "bird@fyard.net", "Cap-Haitien");
const Yayad = new Student("Yayad", "yayad@fyard.net", "Cayes");
const Meg = new Student("Meg", "meg@fyard.net", "Miami");
// Verification
webDevFund.registerStudent(Bird);
webDevFund.registerStudent(Max);
fullStack.registerStudent(Yayad);
fullStack.registerStudent(Meg);
fullStack.registerStudent(Yayad);
【问题讨论】:
-
forEach不返回任何内容。您不能将它用作if语句中的条件(它始终是未定义的,其计算结果为假)。看Array.some。此外,您的测试 (s.email === s.email) 始终正确。如果你使用 Array.some,你必须解决这个问题。
标签: javascript arrays class