限制API请求中的项目



我想问如何将API请求限制为仅5项,因为当前当我访问API时,它返回20项。但我只想显示5。我发现的大多数情况只是在整个对象数组中循环,而不是将其限制在多个项目中。

注意:我无法控制API,因为我只使用移动的API

这是我的代码:

const main = document.getElementById('main')
getMovies(URL_API)
async function getMovies(url) {
const res = await fetch(url)
const data = await res.json()
showMovies(data.results)
}
function showMovies(movies){
main.innerHTML = ''
movies.forEach((movie) => {
const {title, poster_path, vote_average, overview, vote_count} = movie
const movieEl = document.createElement('div')
movieEl.classList.add('movie')
movieEl.innerHTML = `
<img src="${IMAGE_URL + poster_path}" alt="${title}">
<div class="movie-info">
<h3>${title}</h3>
</div>
<div class="movie-rate">
<img src="imgs/star.svg" width="10" height="10" alt="heart">
<span class="colorVote">${vote_average}</span>
<span class="NumberVotes">${vote_count}</span>
</div>
`
main.appendChild(movieEl)
})
}

限制5的另一种方法,替换

movies.forEach((movie) => {

带有

movies.forEach((movie, index) => {
if(index >= 5) return;

您可以将数组切割成块

const main = document.getElementById('main')
getMovies(URL_API)
let chunkIndex = 0; //initialize chunk index
async function getMovies(url) {
const res = await fetch(url)
const data = await res.json()
const chunkSize = 5; //only get 5
const chunks = []
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = data.results.slice(i, i + chunkSize);
chunks.push(chunk);
}
showMovies(chunks[0]); //only use the first chunk for rendering

//TODO: If you have `get more` button
//You can use chunks[chunkIndex] to get more data
//showMovies(chunks[chunkIndex]);
//chunkIndex++; //increase chunk index
}
function showMovies(movies){
main.innerHTML = ''
movies.forEach((movie) => {
const {title, poster_path, vote_average, overview, vote_count} = movie
const movieEl = document.createElement('div')
movieEl.classList.add('movie')
movieEl.innerHTML = `
<img src="${IMAGE_URL + poster_path}" alt="${title}">
<div class="movie-info">
<h3>${title}</h3>
</div>
<div class="movie-rate">
<img src="imgs/star.svg" width="10" height="10" alt="heart">
<span class="colorVote">${vote_average}</span>
<span class="NumberVotes">${vote_count}</span>
</div>
`
main.appendChild(movieEl)
})
}

首先,我会检查您是否可以向您的api发送请求以限制te结果列表。我没有这个api的帐户。但我发现了这个请求:

https://api.themoviedb.org/5/list/{list_id}?page=1&api_key=<<api_key>>

必须返回5个项目。

最新更新