Tengo una clase Student y un método eligibleForPlacements que verifica si un estudiante es elegible para ubicaciones. ¿Cómo itero a través de todos los objetos y verifico si el estudiante es elegible usando el método?
He creado una matriz static allObj = new Array(); que almacena todo el objeto pero no funciona:
class Student { static noOfStudents = 0; static allObj = new Array(); constructor(name1, age, phoneNumber, boardMarks) { this.name = name1, this.age = age, this.phoneNumber = phoneNumber, this.boardMarks = boardMarks Student.noOfStudents += 1; Student.allObj.push(this); } eligibleForPlacements(minMark) { return (age1) => { if (age1 < this.age && this.boardMarks > minMark) { console.log(`${this.name} is eligible for placements`); } else { console.log(`${this.name} is not eligible for placements`); } } } } //created two object and iterating through it const lili = new Student('Lili', 16, '2827384788', 50); const ria = new Student('Ria', 23, '2827384788', 30); for (let i = 0; i < Student.allObj.length; i++) { Student[i].eligibleForPlacements(10)(5); }Te falta .allObj al final
class Student { static noOfStudents = 0; static allObj = new Array(); constructor(name1, age, phoneNumber, boardMarks) { this.name = name1, this.age = age, this.phoneNumber = phoneNumber, this.boardMarks = boardMarks Student.noOfStudents += 1; Student.allObj.push(this); } eligibleForPlacements(minMark) { return (age1) => { if (age1 < this.age && this.boardMarks > minMark) { console.log(`${this.name} is eligible for placements`); } else { console.log(`${this.name} is not eligible for placements`); } } } } const lili = new Student('Lili', 16, '2827384788', 50); const ria = new Student('Ria', 23, '2827384788', 30); for (let i = 0; i < Student.allObj.length; i++) { // add .allObj here Student.allObj[i].eligibleForPlacements(10)(5); }Está intentando leer el índice de la clase Student en sí, no la propiedad allObj ; cambiar Student[i].eligibleForPlacements(10)(5); a Student.allObj[i].eligibleForPlacements(10)(5); y funciona bien:
class Student { static noOfStudents = 0; static allObj = new Array(); constructor(name1, age, phoneNumber, boardMarks) { this.name = name1, this.age = age, this.phoneNumber = phoneNumber, this.boardMarks = boardMarks Student.noOfStudents += 1; Student.allObj.push(this); } eligibleForPlacements(minMark) { return (age1) => { if (age1 < this.age && this.boardMarks > minMark) { console.log(`${this.name} is eligible for placements`); } else { console.log(`${this.name} is not eligible for placements`); } } } } const lili = new Student('Lili', 16, '2827384788', 50); const ria = new Student('Ria', 23, '2827384788', 30); for (let i = 0; i < Student.allObj.length; i++) { Student.allObj[i].eligibleForPlacements(10)(5); }