首页 > 解决方案 > Javascript 将用户的输入存储到二维数组中

问题描述

我试图用用户输入的数据值存储二维。比如说,将学生的测试结果存储到该数组中。我已经设法使用一维数组来做到这一点,但未能将二维数组与用户输入相关联。我检查了许多 2D 数组示例,发现如果使用 Java 而不是 Javascript,这会容易得多,但目前,这是我所知道的唯一语言,我确实想知道如何使用 Javascript 来完成。我也尝试使用位置变量“i”来连接输入和数组,但无法弄清楚。

标签: javascriptmultidimensional-arrayinput

解决方案


我看到您的问题有两种解决方案。第一个是我会怎么做,更有主见,并且使用Objects. 第二个是二维数组。希望有帮助!

个人方法和建议

我认为你最好使用对象而不是 n 维数组。我看到的解决方案提供了您显示的数据:

// Define a student object
function Student(_name, _mark1, _mark2, _mark3) {
  this.name = _name;
  this.mark1 = _mark1;
  this.mark2 = _mark2;
  this.mark3 = _mark3;
}

// Define the array that will hold the students and their marks
var TestResults = [];

// Process HTML
var Name = document.getElementById("Name").value;
var Mark1 = document.getElementById("Mark1").value;
var Mark2 = document.getElementById("Mark2").value;
var Mark3 = document.getElementById("Mark3").value;

// Add new student record
TestResults.push(new Student(Name, Mark1, Mark2, Mark3));

// At any time now you can access the data like so:
// TestResults[index].name gives the name of the student
// TestResults[index].mark1 gives the first mark
// ...
// TestResults[0].Name => Will give you the name of the first student in the array

直接回答你的问题

var TestResults = [];

// For each processed student
TestResults.push([Name, Mark1, Mark2, Mark3]);

// Now you can access your data only by indexes
// TestResults[0][0] will give you the name of the first student
// TestResults[1][1] will give you the first mark of the second student
// ...

推荐阅读