简体   繁体   English

基于用户提示的 Javascript 并行 arrays 问题。 如何停止在循环中超出数组范围?

[英]Issue with Javascript parallel arrays based on user prompt. How to stop going out of array bounds in loop?

I am having trouble with this problem.我遇到了这个问题。 The program ask to take create a program which ask for a use input for the number of students and how many quiz they took that semester.该程序要求创建一个程序,该程序要求输入学生人数以及他们在该学期参加了多少次测验。 The user should then be able to input the data into a parallel array.然后用户应该能够将数据输入到并行数组中。

So far, this is what I have.到目前为止,这就是我所拥有的。

 function getScores() { let studentNames = []; let studentScores = []; var arr = []; let input = ""; let nStudents = parseInt(prompt("How many students are there?")); for (i = 0; studentNames.length < nStudents; i++) { let name = prompt("Enter the students names"); studentNames.push(name); } let nTest = parseInt( prompt( "How many test did the " + studentNames.length + " student each take?" ) ); let temp = nTest * studentNames.length; for (i = 0; i < temp; i++) { while (i < temp) { let score = parseInt( prompt( "What was " + studentNames[i] + "'s Test " + " " + i + " score?" ) ); studentScores.push(score); i++; } } console.log(studentNames); console.log(studentScores); } getScores();

As you can see, There are mutlitple issues.如您所见,存在多个问题。

  1. My second loop will iterate over through the names, but once it gets to the last length of the array, it simply goes over into a new index and gets the value undefined.我的第二个循环将遍历名称,但是一旦到达数组的最后一个长度,它就会简单地进入一个新索引并获取未定义的值。 I tried to stop the loop when it reaches then end, but that is redundant being that I need to enter all of the test scores.我试图在循环到达然后结束时停止循环,但这是多余的,因为我需要输入所有测试分数。
  2. Another issue is that I am iterating through the test in a way that iterates +1 after each new student.另一个问题是,我正在以一种在每个新学生之后迭代 +1 的方式迭代测试。 I don't want that.我不想那样。 I would like each iteration of the loop to say "Test 1" for each student, and then move onto "Test 2" for each student again.我希望循环的每次迭代都为每个学生说“测试 1”,然后再次为每个学生移动到“测试 2”。

I am having trouble understanding where I am going about this wrong.我无法理解我要去哪里解决这个错误。 I know that my loops are just not correct and there is most likely a much easier solution like 2d array, but I am trying to use parallels.我知道我的循环不正确,并且很可能有一个更简单的解决方案,例如 2d 数组,但我正在尝试使用并行。

I am also wondering how these changes will come into play when I have to find the avg, lowest, and higher score for each user and print them to the screen.我还想知道当我必须找到每个用户的平均分、最低分和更高分并将它们打印到屏幕上时,这些更改将如何发挥作用。 I usually find the sums but taking the sum of the whole array, but since I need to put all the score into 1 single array, I do not see how I will be able to dynamically grab the correct scores for each student and calculate them.我通常会找到总和但取整个数组的总和,但由于我需要将所有分数放入 1 个单个数组中,我不知道如何动态获取每个学生的正确分数并计算它们。

It seems like doing this with a parallel array would be VERY difficult, because than we don't know the number of test and students until the user prompt.似乎使用并行数组执行此操作非常困难,因为在用户提示之前我们不知道测试和学生的数量。

If there is an easier way to go about this, I am interested.如果有更简单的方法来 go 关于这个,我很感兴趣。 I am not sure if I am even doing this parallel array method properly and I would love some insight from others, as I am still new to Javascript and arrays.我不确定我是否正确地执行了这种并行数组方法,并且我希望从其他人那里得到一些见解,因为我对 Javascript 和 arrays 还是新手。

Use an object, not two arrays.使用 object,而不是两个 arrays。 I'm going to assume student names are unique (even though in real life they aren't, which is why we use student numbers), so have a single object studentScores and use that as your map:我将假设学生姓名是唯一的(即使在现实生活中他们不是,这就是我们使用学生编号的原因),所以有一个 object studentScores并将其用作您的 map:

const studentScores = {};

const N = parseInt(prompt("How many students are there?"));
for (let i=0; i < N; i++) {
  let name = prompt("Enter the students names");
  if (name) {
    studentScores[name] = 0;
  }
}

const T = get number of tests
Object.keys(studentScores).forEach(function(name) {
  for (let i=0; i<T; i++) {
    let score = parseFloat(prompt(`What did ${name} score on test ${i}?`));
    if (score) {
      studentScores[name] += score;
    }
  }
});

If you absolutely have to use parallel arrays, because you're trying to understand how you would use those, the basic concept is to never push into or pop from a single array.如果您绝对必须使用并行 arrays,因为您试图了解如何使用它们,基本概念是永远不要推入或弹出单个数组。 Your arrays are linked: if you push or unshift, you do that to both.您的 arrays 已链接:如果您推送或取消移动,则对两者都执行此操作。 If you pop or shift, you do that to both:如果你弹出或移位,你对两者都这样做:

function getScores() {
  let input;

  const names = [],
    scores = [];

  // Get the number of students but VERIFY that you got a number:
  input = prompt("How many students are there?");
  const studentCount = parseInt(input);

  // There are many ways to verify this, but using JS coercion through ==
  // works quite well. This is one of the few times that == makes sense.
  if (studentCount == input) {
    for (let i = 0; i < studentCount; i++) {
      let name = prompt(`Please give the name for student number ${i}`);
      if (name) {
        // Here we GUARANTEE that the array positions for
        // this name and the associated score are the same:
        // if we push to `names`, we also push to `scores`,
        // so there is no possibility for the two getting
        // "out of sync" with respect to indexing
        names.push(name);
        scores.push(0);
      }
    }
  }

  input = prompt("How many tests did each student take?");
  const testCount = parseInt(input);

  if (testCount == input) {
    names.forEach(function(name, position) {
      for (let i = 0; i < testCount; i++) {
        input = prompt(`What did ${name} score for test ${i}?`);
        let score = parseFloat(input);
        if (score == input) {
          scores[position] += score;
        }
      }
    });
  }
}

Also note that I've corrected some things in your code: don't assume prompt gives you anything: it can be cancelled, and your code will break if you don't test for that.另请注意,我已经更正了您的代码中的一些内容:不要假设prompt会给您任何东西:它可以被取消,如果您不对此进行测试,您的代码将会中断。 Also, parseInt or parseFloat give not you a number, they may give you a number, so test that they actually do before going into the code that relies on numbers.此外, parseIntparseFloat不会给你一个数字,它们可能会给你一个数字,所以在进入依赖数字的代码之前测试它们实际上是做什么的。

Also, string composition: don't use string + string , use template literals and template in your values.此外,字符串组合:不要使用string + string ,在你的值中使用模板文字和模板。 Get into that habit now, it prevents a lot of string composition related bugs and headaches later, in other code.现在养成这个习惯,它可以防止以后在其他代码中出现很多与字符串组合相关的错误和令人头疼的问题。

Then, note that we're using for (let i=...) : this keeps i scoped to the for loop: it won't exist before it runs, and it won't exist after it's done.然后,请注意我们正在使用for (let i=...) :这使i的范围仅限于 for 循环:它在运行之前不存在,在它完成后也不存在。 Unlike when you use for(i=...) , which is the same as for(var i=...) and actually makes i a function-scoped variable, meaning it already exists before the function code runs, and keeps existing after your loop's done.与使用for(i=...)时不同,它与for(var i=...)相同,实际上使i成为函数范围的变量,这意味着它在 function 代码运行之前已经存在,并保持存在在你的循环完成后。 Which is almost never what you want.这几乎不是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 执行while循环无法使用提示。 Java脚本 - Do while loop not working with prompt. Javascript Javascript 2d数组:越界问题 - Javascript 2d Array: going out of bounds problem 如何根据用户输入提示的数字减少 JavaScript 中的 for 循环? - How to decrement a for loop in JavaScript based upon a number that a user enters into a prompt? 与 Ruby 相比,在 Javascript 中,在遍历数组时,是否不需要“保护”迭代器越界? - Compared to Ruby, in Javascript, when iterating through an array, do you not need to "protect" against going out of bounds with the iterator? JavaScript检查数组越界 - JavaScript Checking Array Out of Bounds Javascript“ while”循环,如果条件为假,如何停止迭代 - Javascript 'while' loop, how to stop iteration if condition is going to be false 在使用提示询问用户输入之前加载html。 - load html before asking for user's input using prompt. 如何重新提示用户(或循环提示),直到用户终止 javascript 中的程序? - how to reprompt the user (or loop a prompt), until user terminates programs in javascript? 简单的Javascript:如何根据用户提示调用函数; - Simple Javascript: How to invoke a function based off user prompt; 如何阻止表单提交进入循环? - How to stop form submit from going into a loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM