陷入一个不那么无限的循环?

Stuck in a not so infinite loop?

我是 JavaScript 的新手,所以请不要针对 "ignorant" 问题攻击我。

在我当前的代码中,我陷入了一个似乎是无限循环(但不是完全无限)的循环,最终可能在我所有的提示都经过 5 次后结束。

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?"));

        }

我不确定我是不是没有正确设置数组或 for 循环,或者我需要做什么才能让它通过并填充数组。

请记住,我是 JavaScript 的新手,所以最基本的、初学者的、简单的答案将是最好的。我现在只是想在基础知识上站稳脚跟。 (:

for 块中的每一行代码运行指定的次数,在本例中为 books.length 次。每次循环运行时,循环计数器(在本例中为 authorName)可用作具有当前值的变量,在本例中它将在 5 次迭代中取值 0 到 4。

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

我想你正在寻找这个:

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] + "?"));
}

这只会触发 5 次,是完成您想要做的事情的更好方法。另外,我会将 authorName 的名称更改为更能描述它的名称。