[英]Searching through Array in javascript based on user input
嘿伙计们,我正在尝试搜索数组并根据用户输入显示搜索结果
我的程序的一个运行是读取一系列学生姓名和他们的分数并确定他们的成绩。 之后,我想搜索一个学生并显示他的姓名、分数和成绩。
目前我到目前为止总是找不到打印学生。
"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 到 3if (studentList[i] == searchName) {
更改为if (studentList[i].name == 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.