[英]How to find id in array object then edit and delete a object in oop javascript?
我编码演示学生管理。 但是下面有问题,请帮助我解决。
要求
id
Name
Age
Point
这是我的代码:
//
function Student(id, name, age, point) {
this.id = id;
this.name = name;
this.age = age;
this.point = point;
}
Student.prototype = {
setId: function (value) {
this.id = value;
},
getId: function () {
return this.id;
},
setName: function (value) {
this.name = value;
},
getName: function () {
return this.name;
},
setAge: function (value) {
this.age = value;
},
getAge: function () {
return this.age;
},
setPoint: function (value) {
this.point = value;
},
getPoint: function () {
return this.point;
},
};
function StudentController(student) {
this.listStudent = [];
this.id = 1;
}
StudentController.prototype = {
addNew: function (name, age, point) {
var student = new Student(this.id, name, age, point);
this.listStudent.push(student);
this.id += 1;
return student;
},
这是函数find id。 但是它总是返回数组对象中的最后一个id。
findId: function (id) {
var student = null;
for (var i = 0; i < this.listStudent.length; i++) {
if (id = this.listStudent[i].getId()) {
student = this.listStudent[i];
}
}
return student;
},
这是功能编辑学生。 但它不能getId
从功能findId();
editStudent: function (student) {
var oldStudent = this.findId(student.getId());
console.log('oldStudent', oldStudent);
for (var x = 0; x < this.listStudent.length; x++) {
if (oldStudent = this.listStudent[x].getId()) {
this.listStudent[x] = student;
}
}
},
此函数也与editStudent()
函数相同。
deleteStudent: function (student) {
var crrentStudent = this.findId(student.getId());
for (var y = 0; y < this.listStudent.length; y++) {
if (crrentStudent.getId() === this.listStudent[y]) {
this.listStudent.splice(y, 1);
}
}
},
学生的此函数排序点> =5。但是看起来不起作用:(
// find point student > = 5
findByPoint: function (point) {
var point = '';
for (var i = 0; i < this.listStudent.length; i++) {
if (this.listStudent[i].getPoint() >= point) {
return point;
}
}
},
showStudent: function () {
console.table(this.listStudent);
},
};
var studentController = new StudentController();
studentController.addNew("Hanh", 20, 8);
studentController.findId(1);
studentController.editStudent();
studentController.deleteStudent();
请帮我解决和解释。 非常感谢 !!
问题非常简单,对于比较运算符, if condition
=
则需要==
进行赋值和加法
更改findId()
函数
findId: function (id) {
var student = null;
for (var i = 0; i < this.listStudent.length; i++) {
if (id == this.listStudent[i].getId()) { // change here
student = this.listStudent[i];
}
}
return student;
},
并在editStudent
函数中
editStudent: function (student) {
var oldStudent = this.findId(student.getId());
console.log('oldStudent', oldStudent);
for (var x = 0; x < this.listStudent.length; x++) {
if (oldStudent == this.listStudent[x].getId()) { //change here
this.listStudent[x] = student;
}
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.