大家好,我正在尝试搜索数组并根据用户输入显示搜索结果

我程序的一个贯穿过程是读取一系列学生的姓名和他们的分数,并确定他们的成绩。之后,我想搜索一个学生并显示他的姓名,分数和成绩。

目前,到目前为止,我一直找不到印刷学生。

"use strict"
const readline = require('readline-sync');

var name, marks;
var studentList = [];

input();
search();

function printList(list) {
    for (const entry of list) {
        // Get a local for `marks` via destructuring
        const {marks} = entry;
        if (marks > 100 || marks < 0) {
            throw new Error(`Invalid 'marks' value: ${marks}`);
        } else if (marks >= 80) {
            entry.grade = 'HD'
        } else if (marks >= 70) {
            entry.grade = 'D'
        } else if (marks >= 60) {
            entry.grade = 'C'
        } else if (marks >= 51) {
            entry.grade = 'P'
        } else { // No `if (marks >= 0)` because we know it is, otherwise we would have thrown an error above
            entry.grade = 'N'
        }
        console.log(entry);
    }

function searchStudent(searchName){
    for (let i = 0; i<= studentList.length; i++){
        if(studentList[i] == searchName){
            console.log(studentList[i]);
        }
        else {
            console.log("student not found");
        }
    }
}

function input() {

    while (true)
    {
        console.log('Please enter the student name (or "end" to end): ');
        const name = readline.question('Student Name: ');
        if (name === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Student Name is' , name);
        const marks = readline.question('Enter marks for ' + name + ': ');
        if (marks === 'end')
        {
            printList(studentList);
            break;
        }
        console.log('Marks for ' + name + ' are ' + marks );
        studentList.push({name:name, marks: parseFloat(marks)});
    }
}

function search() {
    while (true)
    {
        console.log('Please enter the name of student to search for: (or "stop" to end search): ');
        const searchName= readline.question("Student Name: ");


        if(searchName === 'stop'){
            break;
        }
    searchStudent(searchName);
    }
}

最佳答案

您需要解决以下问题:


for (let i = 0; i <= studentList.length; i++) {替换为for (let i = 0; i < studentList.length; i++) {,以便它不会尝试访问不存在的索引。例如如果studentList是长度为4的数组,则索引仅从0到3
if (studentList[i] == searchName) {更改为if (studentList[i].name == searchName) {。否则,您将对象与字符串进行比较。
您的代码所做的是,它遍历studentList中的所有元素,并且对于不是searchName的每个条目,它都会显示“找不到学生”。遍历所有列表项后,您只想打印“找不到学生”。
如果找到要寻找的学生,请使用return关键字提前退出该功能。


因此,您的代码应如下所示:

function searchStudent(searchName) {
  for (let i = 0; i < studentList.length; i++) {
    if (studentList[i].name == searchName) {
      console.log(studentList[i]);
      return;
    }
  }
  console.log('student not found');
}


这是做同一件事的另一种方法:

function searchStudent(searchName) {
  const student = studentList.find(student => student.name === searchName);
  if (!student) {
    console.log('student not found');
    return;
  }
  console.log(student);
}

07-27 14:44