Javascript - How to save prompt input into array

ε祈祈猫儿з 提交于 2019-12-02 13:11:54

问题


I`m having some issue with Javascript. We just started to study it a couple weeks ago and I have to do a work for class:

Need to do a prompt. get 10 numbers input (10 grades) from the user. put the numbers into an array and then do some functions with it.

My question is how do I save the input in the array? We learned about all the loops already. Tried to search online but didn`t found an answer.

I would love if somebody could explain how I do it. Thank you very much.


回答1:


Just try to ask them to input their numbers or grade, separated by a comma and then you can split on it.

var arr = prompt("Enter your numbers").split(",")

Or, ask prompt ten times

var arr = [];
for(var i = 0; i < 10; i++)
   arr.push(prompt("Enter a number");

If you want them to be numbers, just prefix prompt with +, so it becomes a number(provided they're actual numbers) or just do

arr = arr.map(Number);



回答2:


See the explanations in comments:

var arr = [];                               // define our array

for (var i = 0; i < 10; i++) {              // loop 10 times
  arr.push(prompt('Enter grade ' + (i+1))); // push the value into the array
}

alert('Full array: ' + arr.join(', '));     // alert the results



回答3:


<script>
    var grades = [];
    var i;
        for (i = 0; i < 10; i++) {
            grades.push(Number(prompt("Enter your grades:" + (i + 1), "0-100")));
        }
    document.write("Your grades: " + grades);
</script>

Ok so I made this one. The user can enter 10 different numbers to the array and I can display them. Now - I need to caculate the avarage of the numbers and get the highest number.

I would like to have some help withj it, how can I make it?




回答4:


NUMBER_OF_INPUTS = 10;

var i = 0;     // Loop iterator
var userInput; // Input from user
sum = 0; //initialise sum

// Collect inputs
for(i=0; i<NUMBER_OF_INPUTS; i++)
{   userInput = parseInt(prompt('Enter input '+(i+1)+' of '+NUMBER_OF_INPUTS));
    sum += userInput;
    sum /= NUMBER_OF_INPUTS;
}

// Output the average
alert('Average grade: '+ sum.toFixed(2)); //the .toFixed sets it to 2 decimal places


来源:https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!