我试图用用户输入的数据值存储二维。比如说,将学生的测试结果存储到该数组中。我已经成功地使用一维数组做到了这一点,但未能将二维数组与用户输入相关联。我检查了许多 2D 数组示例,发现如果使用 Java 而不是 Javascript,这会容易得多,但目前,这是我所了解的唯一语言,我确实想知道如何使用 Javascript 来完成它。我还尝试过使用位置变量“i”来连接输入和数组,但无法弄清楚。
最佳答案
我看到有两种解决方案可以解决您的问题。第一个是我会如何做,并且更加固执己见,并且使用对象
。第二个是二维数组。希望有帮助!
个人的方法和建议
我认为你最好使用对象而不是 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
// ...
关于Javascript 将用户的输入存储到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438597/