JavaScript 中返回 NaN 的函数
我正在尝试编写一个函数来计算学生对象列表中的平均学生年龄,但是当我运行代码时,该函数将 NaN 作为输出打印出来,
function average_age(){
let total = 0;
students.forEach(s => {
total += Number(s.age);
});
return total/size
}
console.log("Average age is : " + average_age())
这就是我构造数组的方式(我从用户那里获得了输入
const size = 5
let students = [size]
for (let i=1; i<=5; i++){
let name = prompt("Enter student's name: ")
let gender = prompt ("Enter student's gender: ")
students.push({
name: name,
gender: gender,
age:Math.round(Math.random() * (35 - 17 + 1) + 1),
grade:Math.round(Math.random() * (100 + 1))
})
}
//display student info
students.map(s =>{
console.log("Name: " + s.name);
console.log("gender: " + s.gender);
console.log("age: " + s.age);
console.log("grade: " + s.grade);
console.log();
})
)尝试计算学生年龄的总数(删除除法运算)以检查问题是否是除法,但我仍然得到 NaN 作为输出
I am trying to write a function that calculates the average student age in a list of student objects, but when I run the code the function prints NaN as an output
function average_age(){
let total = 0;
students.forEach(s => {
total += Number(s.age);
});
return total/size
}
console.log("Average age is : " + average_age())
this is how i constructed the array ( i got the input from the user)
const size = 5
let students = [size]
for (let i=1; i<=5; i++){
let name = prompt("Enter student's name: ")
let gender = prompt ("Enter student's gender: ")
students.push({
name: name,
gender: gender,
age:Math.round(Math.random() * (35 - 17 + 1) + 1),
grade:Math.round(Math.random() * (100 + 1))
})
}
//display student info
students.map(s =>{
console.log("Name: " + s.name);
console.log("gender: " + s.gender);
console.log("age: " + s.age);
console.log("grade: " + s.grade);
console.log();
})
i tried to calculate the total of student age (removing the divide operation) to check if the problem was the division but i still got NaN as an output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设学生数组采用以下格式(收集输入后):
一种可能的解决方案如下:
Assuming the students array is in the format below (after you collected the inputs):
One possible solution is the following:
您可以检查下面的 3 种方法来解决您的问题:
You can check 3 approaches down there for your problem: