如何使用用户输入填充数组?

时间:2014-03-31 00:46:03

标签: javascript arrays input

你好我正确地尝试将用户输入添加到数组

while (repeat !== "n")
  {
    var Student = prompt("Enter Student Name: ");
    var StudentArr = new Array(Student);
    var mark = parseInt( prompt("Enter Student Mark: ") );
    var markArr = new Array(mark);
    var repeat = prompt ("Do you want to enter another student: y/n");
  }

2 个答案:

答案 0 :(得分:1)

需要在循环外定义数组。

var repeat, studentArr = [], markArr = [];
while (repeat !== 'n' && repeat !== 'N'){
    studentArr.push(prompt("Enter Student Name: "));
    markArr.push(prompt("Enter Student Mark: "));
    repeat = prompt ("Do you want to enter another student: y/n");
}
console.log('studentArr, markArr',studentArr, markArr);

结果:

studentArr,markArr [" Dan"," Bill"] [" A"," B"]

答案 1 :(得分:0)

首先创建存在于while循环范围之外的数组。如果不这样做,只要循环重复,对数组的所有更改都将丢失。

声明新数组时,将n的整数传递给new Array(n)。这决定了为阵列分配的阵列插槽数。所以new Array(5)会创建一个包含5个插槽的数组。如果你将n留空,那么你将获得一个空数组。

var markArr = new Array(); //you can also do var markArr = [];
var StudentArr = new Array();

while (repeat !== "n")
  {
    var Student = prompt("Enter Student Name: ");
    //use the array push() method to add items to your array
    var Student.push(Student);
    var mark = parseInt( prompt("Enter Student Mark: ") );
    markArr.push(mark);
    var repeat = prompt ("Do you want to enter another student: y/n");
  }