Javascript 将用户的输入存储到二维数组中

标签 javascript multidimensional-array input

我试图用用户输入的数据值存储二维。比如说,将学生的测试结果存储到该数组中。我已经成功地使用一维数组做到了这一点,但未能将二维数组与用户输入相关联。我检查了许多 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/

相关文章:

python - Python 3 中是否有类似于 C++ 中的 getchar() 的内置函数?

python - Numpy:如何按整数值缩放整数数组?

python - NumPy 中的 ndarray 和数组有什么区别?

javascript - 在按下按钮时使用 javascript 显示/隐藏 div(并首先隐藏所有 div)

javascript - 淡入淡出加载CSS3动画的最佳方法

python - 在 Python 3 中创建随机空白矩阵(二维数组)?

jquery - 当输入包含特定值时,如何使用 jquery 将类添加到输入

javascript - 单选或复选框输入上的 onclick 函数?

javascript - 使用 Mapbox gl js 将悬停时的弹出窗口添加到自定义标记

javascript - Nodejs async.each 等待第一个循环