【问题标题】:Push item in array and see if item already exist推入数组中的项目并查看项目是否已存在
【发布时间】: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


【解决方案1】:

尝试改用Array.some

if (this.students.some(s => studentToRegister.email === s.email)) {
    console.log(`The student ${studentToRegister.email} is already registered!`);
}

另外,考虑在这种情况下使用MapSet

const map = new Map;

if (!map.has(student.Email)) {
    map.set(student.Email, student);
}
const set = new Set;

if (!set.has(student)) {
    set.add(student);
}

【讨论】:

  • 感谢朋友的帮助。我真的很感激。
【解决方案2】:

你有:

    if (this.students.forEach(s => s.email === s.email)) {

你想要:

    if (this.students.find(s => s.email === studentToRegister.email)) {

查看forEachfind 之间的区别。找到 RETURNS 一个匹配的值,forEach 什么都不返回(因此是假的)。

另外请注意,如果您不打算拥有相同学生详细信息的多个实例,则可以直接比较学生对象而无需查看电子邮件地址。

【讨论】:

    【解决方案3】:

    我不确定程序是如何崩溃的。如果您可以提供非常有用的错误详细信息,但粗略一看,这可能是一个错误:

    if (this.students.forEach(s => s.email === s.email)) {.

    s.email === s.email 将始终评估为真。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多