I have a class Student
and a method eligibleForPlacements
which checks if a student is eligible for placements. How do I iterate through all the objects and check if the student is eligible using the method?
I have created an array static allObj = new Array();
which stores all the object but it isn't working:
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);
}
CodePudding user response:
You're trying to read the index of the Student
class itself, not the allObj
property; change Student[i].eligibleForPlacements(10)(5);
to Student.allObj[i].eligibleForPlacements(10)(5);
and it works fine:
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);
}
CodePudding user response:
You are missing .allObj
at the end
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);
}