Stuck in a not-so-infinite loop?

I am very new to JavaScript, so please do not attack me for "uninformed" questions.

In my current code, I'm stuck with what appears to be an infinite loop (but not completely infinite) that eventually ends 5 times, going through all of my clues.

var authors = [];
                for(var authorName = 0; authorName < books.length; authorName++)
            {
                authors[0]=parseFloat(prompt("Who wrote War and Peace?"));
                authors[1]=parseFloat(prompt("Who wrote Huckleberry Finn?"));
                authors[2]=parseFloat(prompt("Who wrote The Return of the Native?"));
                authors[3]=parseFloat(prompt("Who wrote A Christmas Carol?"));
                authors[4]=parseFloat(prompt("Who wrote Exodus?"));

        }

      

I'm not sure. Unless I just set up the array correctly or the for loop or what I need to do to get it to go through and fill the array.

Please keep in mind that I am very new to JavaScript, so the most basic, beginner, simple answers will be the best. I'm just trying to gain a foothold in the basics for now. (:

+3


source to share


2 answers


I think you are looking for this:

var bookNames = [
    "War and Peace?",
    "Huckleberry Finn?",
    "The Return of the Native?",
    "A Christmas Carol?",
    "Exodus?"
];

for(var authorName = 0; authorName < books.length; authorName++)
{
   authors[authorName]=parseFloat(prompt("Who wrote " + bookNames[authorName] + "?"));
}

      



This will only fire 5 times and is the best way to do what you are trying to do. Also, I would change the name authorName

to something that better describes what it is.

+1


source


Each line of code in the block for

is executed as many times as specified, in this case, books.length

times. Every time the loop starts the loop counter, in this case it authorName

is available as a variable with its current value, in this case it will take values ​​from 0 to 4 for 5 iterations.



for(var authorName = 0; authorName < books.length; authorName++)
{
  authors[authorName] = prompt("Who wrote " + books[authorName] + "?");
}

      

0


source







All Articles