我有一个关于数组的问题。如何制作包含多个员工的数组并使用该名称打印显示有关员工的所有详细信息,并且同名员工也打印但选择我的?
指导我如何制作这种类型的软件程序,这可能吗?因为我是信息技术的初学者。
运行此程序:
class Employee {
name: string;
age: number;
position: string;
department: string;
constructor(name: string, age: number, position: string, department: string) {
this.name = name;
this.age = age;
this.position = position;
this.department = department;
}
toString(): string {
return `Name: ${this.name}, Age: ${this.age}, Position: ${this.position}, Department: ${this.department}`;
}
}
const employees: Employee[] = [
new Employee("John Doe", 30, "Software Engineer", "IT"),
new Employee("Jane Smith", 28, "Data Analyst", "Finance"),
new Employee("John Doe", 45, "Project Manager", "IT"),
new Employee("Alice Johnson", 35, "HR Manager", "HR"),
];
function searchAndPrintEmployee(name: string): void {
const matchingEmployees = employees.filter(employee => employee.name === name);
if (matchingEmployees.length === 0) {
console.log(`No employee found with the name: ${name}`);
return;
}
if (matchingEmployees.length === 1) {
console.log(matchingEmployees[0].toString());
} else {
console.log(`Multiple employees found with the name: ${name}`);
matchingEmployees.forEach((employee, index) => {
console.log(`${index + 1}. ${employee.toString()}`);
});
const choice = parseInt(prompt("Enter the number of the employee you want to see details for: ") || "0", 10) - 1;
if (choice >= 0 && choice < matchingEmployees.length) {
console.log(matchingEmployees[choice].toString());
} else {
console.log("Invalid choice.");
}
}
}
// Example usage
const nameToSearch = prompt("Enter the name of the employee you want to search for: ");
if (nameToSearch) {
searchAndPrintEmployee(nameToSearch);
}
说明
我认为,当您对 TypeScript 和一般编程更加熟悉时,可以通过更多功能来扩展它。