TypeScript 示例代码:
typescriptinterface Student {name: string;score: number;rank: number; // 添加 rank 属性}function rank(students: Student[]): Student[] {students.sort((a, b) => b.score - a.score);// 遍历排序后的学生数组,为每个学生对象添加名次let
TypeScript 示例代码:
typescriptinterface Student {name: string;score: number;rank: number; // 添加 rank 属性}function rank(students: Student[]): Student[] {students.sort((a, b) => b.score - a.score);// 遍历排序后的学生数组,为每个学生对象添加名次let
在上面的示例中,我们在 Student 接口中添加了一个 rank 属性,表示学生的名次。在 rank 函数中,我们使用一个变量 currentRank 来追踪当前的名次,然后在遍历学生数组时为每个学生对象设置相应的名次。如果有多个学生分数相同,它们将被分配相同的名次。最后,我们将结果打印到控制台上。
请注意,我们在示例用法中将 rank 属性初始化为 0,但在 rank 函数中会被正确地更新。这样,你就可以在返回的学生数组中看到每个学生的名次信息了。
使用 Lodash:
typescriptimport _ from 'lodash';interface Student {name: string;score: number;rank: number; // 添加 rank 属性}function rank(students: Student[]): Student[] {const sortedStudents = _.orderBy(students, 'score', 'desc');
我们首先使用 groupBy 函数将学生数组按照分数进行分组。然后,我们使用 flatMap 函数遍历每个分组,并为每个学生对象设置相应的名次。在设置名次时,我们使用一个变量 currentRank 来追踪当前的名次,并根据分组的长度更新名次值。
这样,无论学生的分数是否相同,都能正确地为每个学生设置名次。
更新于2026-09-19
更新于2026-09-19