我在显示数组内部的角色名称值时遇到问题

问题描述 投票:0回答:1

我正在开发 Library Express 应用程序,我正在使用虚假数据轻松在屏幕上显示值。

const PopularBooks = [
  {
    id: 1,
    title: "Harry Potter",
    characters: [
      {
        id: 1,
        name: "Harry Potter",
      },
      {
        id: 2,
        name: "Hermione",
      },
      {
        id: 3,
        name: "Ron",
      },
    ],
  {
    id: 2,
    title: "Lord of the Rings",
    characters: [
      {
        id: 4,
        name: "Frodo",
      },
      {
        id: 5,
        name: "Legolas",
      },
      {
        id: 6,
        name: "Gandalf",
      },
    ],
  },
];

我能够很好地显示所有内容,只是在显示角色名称时遇到问题。

    <div class="description">
      <h1><%= book.title %></h1>
    </div>
  </div>
  <div class="data-m1">
    <h4>Characters</h4>
    <div class="characters">
      <% for (let i = 1; i < 4; i++) { %>
      <div class="portrait">
        <img class="book-c" src="/images/book-c-1.png" alt="book" />
        <p><%= book.characters[0].name %></p>
      </div>
      <% } %>
    </div>
  </div>

当我输入

<p><%= book.characters[0].name %></p>
时,它会显示
Harry Potter
三次。但是当我将
[0]
更改为
[i]
以便动态显示每个人的名字时,它给了我这个错误:
Cannot read properties of undefined (reading 'name')
。我想知道是否有更好的方法来绘制它,因为我似乎找不到任何方法。

如果您想知道的话,这就是我如何获得

book
的值。

router.get("/books/:title", function (req, res, next) {
  const bookId = parseInt(req.params.title);
  const book = data.PopularBooks.find((book) => book.id === bookId);
  res.render("books", { book });
});
javascript express ejs
1个回答
0
投票

数组索引从0开始。

改变

 <% for (let i = 1; i < 4; i++) { %>

 <% for (let i = 0; i < 3; i++) { %>
© www.soinside.com 2019 - 2024. All rights reserved.