我正在学习如何在Javascript中构建构造函数,到目前为止一直很好,但我正在努力如何制作一个从数组中删除特定项的方法。
每当我调用Manager.fireEmployee(nameOfEmployee)从阵列中删除该员工时,我都希望这样做。
每当我从构造函数中创建新员工时,还有一种方法可以在数组中自动推送吗?
以下是代码:
class Employee {
constructor(name, department) {
this.name = name;
this.department = department;
}
whoAreYou() {
return `My name is ${this.name} and I am working in ${this.department} department`;
}
};
class Manager extends Employee {
constructor(name) {
super(name, 'General');
}
fireEmployee(nameOfEmployee){
// how to make this method so when I type the name of the employee it will remove it from the array?
}
};
class SalesPerson extends Employee {
constructor(name, quota) {
super(name, 'Sales', quota);
this.quota = quota;
}
};
let michael = new Manager('Michael');
let pam = new Employee('Pam', 'Marketing');
let jim = new SalesPerson('Jim', '1000');
let dwight = new SalesPerson('Dwight', '1200');
let arr = [pam, jim, dwight];
答案 0 :(得分:1)
我为您Manager
课采用略有不同的方法,使其将员工作为一个数组。然后,您可以通过Manager
实例轻松调用所有方法来操作employees数组,例如
michael.addEmployee(pam);
michael.fireEmployee(pam);
class Manager extends Employee {
constructor(name) {
super(name, 'General');
this.employees = [];
}
addEmployee(employee) {
if (employee) this.employees.push(employee);
}
fireEmployee(employee){
this.employees.splice(this.employees.indexOf(employee), 1);
}
getEmployees() {
return this.employees;
}
}
现在试试这个:
class Employee {
constructor(name, department) {
this.name = name;
this.department = department;
}
whoAreYou() {
return `My name is ${this.name} and I am working in ${this.department} department`;
}
}
class Manager extends Employee {
constructor(name) {
super(name, 'General');
this.employees = [];
}
addEmployee(employee) {
if (employee) this.employees.push(employee);
}
fireEmployee(employee) {
this.employees.splice(this.employees.indexOf(employee), 1);
}
getEmployees() {
return this.employees;
}
}
class SalesPerson extends Employee {
constructor(name, quota) {
super(name, 'Sales', quota);
this.quota = quota;
}
}
let michael = new Manager('Michael');
let pam = new Employee('Pam', 'Marketing');
let jim = new SalesPerson('Jim', '1000');
let dwight = new SalesPerson('Dwight', '1200');
michael.addEmployee(pam);
michael.addEmployee(jim);
michael.addEmployee(dwight);
console.log(michael.getEmployees());
michael.fireEmployee(pam);
console.log(michael.getEmployees());

答案 1 :(得分:0)
如果您正在询问如何删除类实例以及数组,那么这就是解决方案。
fireEmployee(nameOfEmployee){
var arrayIdx;
for(var i=0;i<arr.length;i++){
if(arr[i].name == nameOfEmployee){
arrayIdx = i;
}
}
delete arr.splice(arrayIdx,1); // removes from the array as well as the class instance
}
并推送你可以使用函数中的推送方法arr.push(employeeClassInstance)