gpt4 book ai didi

Javascript 使用 readline 添加到数组

转载 作者:行者123 更新时间:2023-12-01 00:09:11 26 4
gpt4 key购买 nike

我试图重复获取 2 个输入并将它们存储到一个数组中,直到键入“end”一词。但是,我在 console.log(studentList[i]);

处未定义

编辑:在你们的帮助下,我能够将值存储到数组中。现在我想做的是为输入的每个分数给出一个“等级”。然而,无论我输入什么数字,我的所有成绩都获得“HD”。

const readline = require('readline-sync');

var name, marks;
var studentList = [];

Input();

function printList(list) {
for (let i = 0; i < studentList.length; i += 1) {
var grade;
if ((marks <= 100) && (marks => 80)){
grade = 'HD'
studentList[i][2] = grade;

}
else if ((marks <= 79) && (marks => 70))
{
grade = 'D'
studentList[i][2] = grade;

}
else if ((marks <= 69) && (marks =>60))
{
grade = 'C'
studentList[i][2] = grade;

}
else if ((marks <= 59) && (marks =>51))
{
grade = 'P'
studentList[i][2] = grade;

}
else if ((marks < 50) && (marks =>0))
{
grade = 'N'
studentList[i][2] = grade;

}
console.log(studentList[i]);
}

}

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

如有任何建议,我们将不胜感激!谢谢!

最佳答案

您主要需要将 .Length 更改为 .length,并且必须使用 while 循环与 while 循环中出现的中断(一旦键入“end”)相结合,以提供您想要打印的列表。通过更改 if 语句的位置,您可以调整何时发生中断以及何时读取用户输入。

const readline = require('readline-sync');

var name, marks;
var studentList = [];

Input();

function printList(list) {
for (let i = 0; i < list.length; i += 1) {
console.log('list[i]', list[i]);
}
}

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

关于Javascript 使用 readline 添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60177246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com