Uncaught ReferenceError: person4未定义,删除不存在员工时出错求助
问题分析与解决
错误根源
你遇到的Uncaught ReferenceError: person4 is not defined,和你写的removeEmployee里的else语句无关——person4这个变量从始至终都没被声明过。JS引擎在执行accountsDept.removeEmployee(person4)时,找不到名为person4的变量,直接抛出错误,根本没机会进入removeEmployee函数执行你写的不存在判断逻辑。
解决办法
方案1:先定义person4实例(测试用)
如果只是想验证“删除部门中不存在的员工”的提示逻辑,先声明person4变量:
// 先定义person4实例,哪怕不加入部门 let person4 = new Employee("Tom", 1500, "01/01/2021"); // 现在调用removeEmployee会进入else分支,打印提示 accountsDept.removeEmployee(person4);
方案2:修改方法,支持按员工名字删除(更实用)
实际开发中,很少会拿着员工实例去删除,通常用名字查找。可以修改removeEmployee方法:
removeEmployee(employeeName) { // 按名字查找员工索引 let index = this.employees.findIndex(item => item.name === employeeName); if (index > -1) { this.employees.splice(index, 1); console.log(`已删除员工${employeeName}`); } else { console.log(`员工${employeeName}不在该部门中`); } }
调用时直接传名字即可,无需提前定义变量:
accountsDept.removeEmployee("Tom");
额外优化建议
- Department无需继承Employee
部门和员工是包含关系,不是继承关系。去掉继承逻辑,避免冗余属性:
class Department { constructor(name) { this.name = name; this.employees = []; } // addEmployee、removeEmployee等方法保留 }
- 简化removeEmployee的条件判断
原代码里的else if (index === -1)可以直接改成else,因为indexOf的结果只有两种可能:找到(>-1)或没找到(-1):
removeEmployee(person) { let index = this.employees.indexOf(person); if (index > -1) { this.employees.splice(index, 1); } else { console.log("This person isn't in the department"); } }
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

