[英]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.