首页 > 解决方案 > 只有三个中的两个导致循环显示数组元素

问题描述

我似乎无法弄清楚为什么我不断获得第一排和第三排。由于某种原因,我跳过了第二名。这是我的代码

//define books and authors
var books = [
    { title: "Data Structures and Algorithm Analysis in C++",
      publisher: "Pearson",
      authors: [
       {firstName: "Mark", lastName: "Weiss" }]
      },

    { title: "Foundations of Finance",
      publisher: "Pearson",
      authors: [
       {firstName: "Arthur", lastName: "Keown" },
       {firstName: "John", lastName: "Martin" }]
      },

    { title: "Literature for Composition",
      publisher: "Longman",
      authors: [
       {firstName: "Sylvan", lastName: "Barnet" },
       {firstName: "William", lastName: "Cain" },
       {firstName: "William", lastName: "Burto" }]
      }
 ];
 
function outputBooks() {
    for (i=0; i<books.length; i++) {
       document.write("<h2>" + books[i].title + "</h2>");
       document.write("<strong>" + books[i].publisher + "</strong>"+ "<br>" + "<br>");
       outputAuthors(books[i]);
    }

 
 function outputAuthors(book) {
    for (i=0; i<book.authors.length; i++) {
      document.write("Author's Name: ");
      document.write(book.authors[i].firstName + ' ' + book.authors[i].lastName + "<br>");
    }
 }
}
 outputBooks();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <script type="text/javascript" language="javascript" src="ass1_q1.js">
        </script>
    </div>
</body>
</html>

我正在尝试编写一个 JS 代码来显示带有作者姓名的三本书的标题。有什么我想念的吗?

标签: javascriptarraysloopsmultidimensional-array

解决方案


我相信问题在于您是全局定义的i,因此 outputAuthors 正在更改 outputBooks 的索引。这可以通过更改两个 for 循环中的代码来轻松解决,for (let i = 0 ...以便每个范围都有自己的变量i


推荐阅读