提示时存储阵列

时间:2017-02-27 03:29:05

标签: javascript arrays prompt

我之前问了一个类似的问题,但我不清楚,我正在学习如何在这里提出正确的问题。我提示用户输入一个数字,该数字将是数组的大小,然后循环以使它们用数字填充数组,直到它们达到之前声明的大小。我的问题是如何使用用户的输入正确存储数组。

function getNumber() {

      var el = document.getElementById("demo");

      // Get the user's input and convert it to a number
      var size = parseInt(prompt("Please enter the size of the array"),10);


        var entries = parseInt(prompt("Enter an integer"),10);

        var userInput = new Array();
        while (entries < size){
             var entries = parseInt(prompt("Enter an integer"),10);
             userInput.push(entries);
             userInput = entries.split(" ");

        }

      // Store the user's input to our global variable
      //userInput[] = entries; 

      // Set up a string that will become the output.

      //display iterations
      el.textContent = userInput[entries];

    }

1 个答案:

答案 0 :(得分:2)

我会把代码写得略有不同:

function getNumber() {

    var el = document.getElementById("demo");

    // Get the user's input and convert it to a number
    var size = parseInt(prompt("Please enter the size of the array"),10);

    // array that will store user input
    var userInput = [];
    while (userInput.length < size){
         var entries = parseInt(prompt("Enter an integer"),10);
         userInput.push(entries)
    }
  //join array element with a space to display
  el.textContent = userInput.join(" ");

}