Javascript - 如何将提示输入保存到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28252888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - How to save prompt input into array
提问by Peter Toth
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:
我在使用 Javascript 时遇到了一些问题。我们几周前才开始研究它,我必须为课堂做一项工作:
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.
需要做一个提示。获取用户输入的 10 个数字(10 个等级)。将数字放入一个数组中,然后用它做一些函数。
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.
如果有人能解释我是如何做到的,我会很高兴。非常感谢。
回答by Amit Joki
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 promptten times
或者,问prompt十次
var arr = [];
for(var i = 0; i < 10; i++)
arr.push(prompt("Enter a number");
If you want them to be numbers, just prefix promptwith +, so it becomes a number(provided they're actual numbers) or just do
如果你想他们是数字,只是前缀prompt用+,所以它成为了许多(提供他们实际的数字),或只是做
arr = arr.map(Number);
回答by Shomz
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
回答by Peter Toth
<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.
好的,所以我做了这个。用户可以在数组中输入 10 个不同的数字,我可以显示它们。现在 - 我需要计算数字的平均值并获得最高数字。
I would like to have some help withj it, how can I make it?
我想得到一些帮助,我该怎么做?
回答by user5856142
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

