TypeScript中如何根据站点名直接访问对应学生数组优化查询?
Absolutely! You can absolutely optimize this by pre-processing your array into a lookup structure (like a Map or a plain object) that lets you access the student array for a given stop in O(1) time, instead of traversing the entire array every time. Here's how to do it cleanly in TypeScript:
Step 1: Add Type Safety (Optional but Recommended)
First, let's define clear types to keep everything type-safe and self-documenting:
type StopStudentGroup = { stop: string; students: string[]; }; // Your original array, now typed let res: StopStudentGroup[] = [ { stop: "stop1", students: ["Maria", "Mario"] }, { stop: "stop2", students: ["Giovanni", "Giacomo"] } ];
Step 2: Create a Lookup Structure
You have two solid options here—pick whichever fits your use case best:
Option 1: Use a Map (Flexible, Great for Dynamic Keys)
Maps are ideal if you might ever use non-string stop identifiers, or if you want access to built-in map utilities:
// Generate the lookup once (run this after res is initialized or updated) const stopToStudents = new Map<string, string[]>( res.map(group => [group.stop, group.students]) );
Option 2: Use a Plain Object (Lightweight, Familiar Syntax)
If you know your stop names are valid, non-special strings, a plain object is a lightweight, easy-to-read choice:
const stopToStudents: Record<string, string[]> = Object.fromEntries( res.map(group => [group.stop, group.students]) );
Step 3: Rewrite checkStudent for Speed
Now your function can skip traversing the entire res array and jump straight to the student list for the target stop:
function checkStudent(stopName: string, studentName: string): boolean { // Fetch the student array (returns undefined if the stop doesn't exist) const students = stopToStudents.get(stopName); // Use this line for Map // OR for plain object: const students = stopToStudents[stopName]; // If the stop doesn't exist, return false right away if (!students) return false; // Check if the student is in the array (includes() is clean and readable) return students.includes(studentName); }
Why This Is Better
- Your original approach was O(n + m): O(n) to find the stop in the array, then O(m) to scan the student list.
- With the lookup structure, it's O(m) (just scanning the student list) because accessing the stop's array is an instant O(1) operation.
- This becomes way more noticeable if you have lots of stops, or if you call
checkStudentfrequently.
Quick Note for Dynamic Data
If your res array changes over time (e.g., adding/removing stops), make sure to update the lookup structure whenever res is modified. Regenerating the lookup on each change is trivial and keeps your data in sync.
内容的提问来源于stack exchange,提问作者CodeRonin

