数据不会出现:无法读取未定义的属性'slice'

问题描述 投票:-1回答:3

我正在尝试显示来自API的一些数据,但收到错误。我能够将其作为HTML打印到控制台,但不能打印到网页上。我收到的错误是:无法读取未定义的属性“切片”。我不想使用切片,但是我不确定在不使用切片的情况下如何显示数据。如何在不使用切片的情况下显示此数据?数据在对象中

// The first section of data from the API - showing the data structure
{
"id": 1,
"url": "http://www.tvmaze.com/shows/1/under-the-dome",
"name": "Under the Dome",
"type": "Scripted",
"language": "English",
"genres": [
"Drama",
"Science-Fiction",
"Thriller"
],
"status": "Ended",
"runtime": 60,
"premiered": "2013-06-24",
"officialSite": "http://www.cbs.com/shows/under-the-dome/",
"schedule": {
"time": "22:00",
"days": [
"Thursday"
]
},
// Printing the data to the console
//fetch('https://api.tvmaze.com/shows/1?embed=episodes') 
//.then((resp) => resp.json()) 
//.then(function (data) {
//   console.log(data)
//})
fetch('https://api.tvmaze.com/shows/1?embed=episodes') 
.then((resp) => resp.json()) 
.then(function (data) {
   const text = document.querySelectorAll(".text")
    data.results.slice(0, 4).forEach((div, i) => { 
    text[i].innerHTML = ` <h2>${div.url}</h2> 
    <p><strong>${div.name}</strong></p>
    `
      }) 
    })
<!DOCTYPE html>
<html>
    <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <link href="https://fonts.googleapis.com/css?family=Alatsi|Dancing+Script|Roboto&display=swap" rel="stylesheet">
            <script src="tv.js"></script>

            <link rel="stylesheet" href="tv.css">
    </head>
    <body>
        <div class="navbar">
            <ul>
                    <li class="header"><h1>Entertainment</h1></li>
                    <li><a href="tv.html">TV</a></li>
                    <li><a href="books.html">Books</a></li>
                    <li><a href="movies.html">Movies</a></li>
                    <li><a href="index.html">Home</a></li>
                  </ul>
        <div class="text">
            </div>
        </div>
    </body>
</html>
javascript html fetch slice
3个回答
1
投票

问题是在这种情况下,API不会返回数组,它只是一个对象。切片仅在数组上调用时才有效。


0
投票

您可以在更新用户界面之前检查data.results数组中是否包含至少5个元素

...

data.results && data.results.length >= 5 && data.results.slice(0, 4).forEach ...

...

0
投票

Object.values可用于将对象转换为数组:

Object.values(data.results).slice(0, 4).forEach((div, i) => { 
© www.soinside.com 2019 - 2024. All rights reserved.