简体   繁体   中英

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. 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. You need to change the condition to i < marks.length to get the desired result.

 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.

Im javascript concatenates, NaN is not a number;

Try to do this:

parseInt("1") + parseInt("1")

instead of 1 + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM