+ 1

JAVASCRIPT: 39.2 Practice - Array Properties & Methods

In JavaScript course, I am having a hard time to understand one part of the given code. The goal of the program is to get the sum of all gained points for each passed level. Passed level is an input (which will be the length of the array). The next inputs are the points for each level (depending on the length of the array). The way I understand the code below, it appears that the program accepts 3 inputs: - levels - points - elem The question is, what is the purpose of the "elem" variable? I am having a hard time to understand it since I am also practicing these JavaScript exercises using my computer web browser and a text editor (visual studio code). function main() { //take the number of passed levels var levels = parseInt(readLine(),10); var points = new Array(); var count = 0; while(count<levels){ var elem = parseInt(readLine(),10); points[count] = elem; count++; } var sum = 0; //calculate the sum of points //output console.log(sum);

5th Oct 2021, 11:06 PM
Rolly U. Valdemoro Jr.
Rolly U. Valdemoro Jr. - avatar
3 ответов
+ 2
The word "elem" is commonly used as a short for "element". In this case, variable <elem> refers to array element, and is used to store input of point(s) given, and it is converted into decimal (base 10) integer. var elem = parseInt(readLine(), 10); Once <elem> had been read, it will be assigned as element in array <points>, and is stored at index <count>. points[count] = elem; To get through this, you need to move the definition of variable <sum> up, after the definition of variable <count> and before the `while` loop. And then, you can add <elem> to <sum> inside the while loop, place this line before incrementing variable <count> while( ... ) { var elem = ...; ... sum += elem; count++; } P.S. I don't know if it was a typo, but it looks like you missed a closing curly bracket for the main() function. You'll have to put that in to make it work.
5th Oct 2021, 11:41 PM
Ipang
+ 1
Hi Ipang, Thank you for this, it was indeed a typo. I've followed your instructions. I can't believe how simple the solution is but somehow difficult to understand. I guess I have to review some topics especially looping statements but thank you for this. I really appreciate it. Regards, Rolly
5th Oct 2021, 11:56 PM
Rolly U. Valdemoro Jr.
Rolly U. Valdemoro Jr. - avatar
+ 1
You're most welcome ... Don't worry, you'll get it all figured out 👌
5th Oct 2021, 11:58 PM
Ipang