数组中的多个员工数组,s方法(推送和过滤)

问题描述 投票:0回答:1

我有一个关于数组的问题。如何制作包含多个员工的数组并使用该名称打印显示有关员工的所有详细信息,并且同名员工也打印但选择我的?

指导我如何制作这种类型的软件程序,这可能吗?因为我是信息技术的初学者。

typescript
1个回答
0
投票

运行此程序:

  • 将完整代码保存在 TypeScript 文件中(例如,employeeSearch.ts)。
  • 使用 TypeScript 将 TypeScript 文件编译为 JavaScript 编译器(例如 tsc employeeSearch.ts)。
  • 在浏览器中打开生成的 JavaScript 文件或在 Node.js 环境。

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);
}

说明

  1. 员工类别:定义员工的姓名、年龄、职位和 部门。
  2. employees Array:保存多个 Employee 对象。
  3. searchAndPrintEmployee 函数:按姓名搜索员工, 处理多个匹配项,并打印所选员工的 详细信息。
  4. 提示:用于在网络浏览器环境中获取用户输入。你 如果您正在运行此输入法,可以将其替换为任何其他输入法 不同的环境。

我认为,当您对 TypeScript 和一般编程更加熟悉时,可以通过更多功能来扩展它。

© www.soinside.com 2019 - 2024. All rights reserved.