Skip to content
Advertisement

Only getting two of three result in loop to display array elements

I can’t seem to figure out why I keep getting 1st and 3rd row. I am skipping 2nd for some reason. Here’s my code

//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>

I am trying to write a JS code to display the title of three books with the authors’ names. Is there anything I’m missing?

Advertisement

Answer

I believe the issue is that you are globally defining i, so outputAuthors is changing the index for outputBooks. This can easily be fixed by changing the code in both for loops to for (let i = 0 ... so that each scope has it’s own variable i

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement