[英]I am running this javascript code but it is giving me an.. error please tell me what is wrong because I think the code is correct?
let marks_of_students = [100,100,40] function FindGrade(marks) { let sum = 0; for (let i = 0;i <= marks.length; i++) { sum += marks[i]; console.log(sum); } return sum; } console.log(FindGrade(marks_of_students));
I don't know why I'm seeing this NaN printing along side the sum.我不知道为什么我看到这个 NaN 在总和旁边打印。 Someone please help what did I do wrong?
有人请帮助我做错了什么?
You are trying to loop over the mark_of_students array with a condition i <= marks.length
which means the loop will try to find marks[3]
in the last iteration which doesn't exist.您正在尝试使用条件
i <= marks.length
循环遍历 mark_of_students 数组,这意味着循环将尝试在最后一次迭代中找到不存在的marks[3]
。 You need to change the condition to i < marks.length
to get the desired result.您需要将条件更改为
i < marks.length
以获得所需的结果。
let marks_of_students = [100, 100, 40] function FindGrade(marks) { let sum = 0; for (let i = 0; i < marks.length; i++) { sum += marks[i] } return sum } console.log(FindGrade(marks_of_students))
try to convert a object into a integer by command parseInt(object) to sum.尝试通过命令 parseInt(object) 将 object 转换为 integer 以求和。
Im javascript concatenates, NaN is not a number; Im javascript 连接,NaN 不是数字;
Try to do this:尝试这样做:
parseInt("1") + parseInt("1") parseInt("1") + parseInt("1")
instead of 1 + 1而不是 1 + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.