如何在输入时通过提示添加输入到数组中的数据,然后除以数组大小为4的数字?我唯一需要帮助的是将输入的数据相加并将其除以得到显示的平均值。
<html>
<body>
<script type="text/javascript">
// declare variables and constants
var SIZE = 4 // array size
var gradeArray // array variable
var gradeAvg // grade average variable
var avgCalc = parseFloat(avgCalc); // variable used to store avg grade
var letGrad = "" // variable used to store Letter Grade
var userInput // variable used for while function
var index // loop variable
var BR = "<br></br>" // page break
var ES = "" // empty string
var semi = ":"
// Create Array
gradeArray = new Array(SIZE);
}
// Create Loop structure for user grade input and ask if input is correct
while (userInput != "Y") {
for (index = 0; index < SIZE; index++) {
gradeArray[index] = prompt("Enter your grades # " + (index + 1) + ":" + ES);
}
// Create display function for loop structure, Displays user input of grades
document.write("Grades Entered:" + BR);
for (index = 0; index < SIZE; index++) {
document.write("The grades you entered are: ");
document.write(gradeArray[index] + BR);
}
userInput = prompt("Are the these grades correct? (Y/N)");
if (userInput == "Y") {
document.write("Thank you!" + BR);
}
}
// Create selection structure. This structure gives the average a letter grade
if (avgCalc >= 90) {
letGrad = "A";
}
else if (avgCalc >= 80) {
letGrad = "B";
}
else if (avgCalc >= 70) {
letGrad = "C";
}
else if (avgCalc >= 60) {
letgrad = "D";
}
else if (avgCalc < 60) {
letGrad = "F";
}
// Display results -- display's results
document.write("Your average is: " + avgCalc + semi + letGrad + BR);
document.write("Thank you for using Average Calculator!");
</script>
</body>
</html>
答案 0 :(得分:0)
您可以使用Array reduce()
方法。它需要一个累加器和一个值,将它们相加并存储到累加器中。像这样:
var gradeSum = gradeArray.reduce(function(total, n){
return total + n
});
这将为您提供存储在阵列中的所有等级的总和。 你只需要像那样划分它
var med = gradeSum/gradeSum.length
现在您的med
var将具有您想要的值!
在此处进一步了解Array reduce方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
答案 1 :(得分:0)
我明白了!就像我知道有一种更简单的方法。我是业余程序员。你们这些人比我更先进,所以你的例子(对你来说很简单)对我来说很先进。
// Welcome user
document.write("Welcome to Grade Average Calculator" + BR);
// Create Array
gradeArray = new Array(SIZE);
// Create Loop structure for user grade input and ask if input is correct
while (userInput != "Y") {
for (index = 0; index < SIZE; index++) {
gradeArray[index] = prompt("Enter your grades # " + (index + 1) + ":" + ES);
gradeSum = +gradeArray[0] + +gradeArray[1] + +gradeArray[2] + +gradeArray[3];
avgCalc = gradeSum / 4;
}