javascript - 从数组中获取前 6 个元素
问题描述
我想显示数组中的前 6 个元素。我正在使用 API 'themoviedb'
。
我正在从 API 获取数据并将数据存储在数组中。
var url = "https://api.themoviedb.org/3/tv/popular?api_key=YOURKEY&language=en-US&page=1";
var img = "https://image.tmdb.org/t/p/w500"
var tvSeriesImg = [];
var request = new XMLHttpRequest(); // New instance of XMLHttpRequest
request.open('GET', url, true); // Open the connection using the 'GET' Method
request.onload = function(){ // Create an onload function this is where the data is displayed on the webpage
var data = JSON.parse(this.response); // Creating a data variable where our JSON is parsed and stored.
if(request.status >= 200 && request.status < 400){ // Check the request status.
data.results.forEach(results => { //Looping through the JSON Array
const popTvSeries = document.getElementById('tv-series-data');
const popTvSeriesCard = document.createElement('div');
popTvSeriesCard.setAttribute('id', 'card');
popTvSeries.appendChild(popTvSeriesCard);
tvSeriesImg.push(results.poster_path);
//Get the first 6 items from the array!!
console.log(tvSeriesImg.slice(0, 6));
const tvImage = document.createElement('img');
tvImage.src = img + tvSeriesImg.slice(0, 6);
tvImage.setAttribute('id', 'movieThumb');
popTvSeriesCard.appendChild(tvImage);
});
}
}
request.send();
我曾尝试使用 slice 方法,但出现以下错误:
解决方案
这是一个简化的 forEach 可以解决您的问题。
const cards = document.getElementById('tv-series-data')
results.forEach(result => {
const card = document.createElement('div')
card.id = result.id // ID's should be unique
card.innerHTML = `<img src="${img}${result.poster_path}">`
cards.appendChild(card)
})
推荐阅读
- haskell - 比较 Haskell 元组中的空列表
- python - python 3中的排序和数字生成问题
- c# - 如何在 C# 中从 JSON 节点路径创建 JSON 对象
- javascript - 我想从js中的字符串中删除一些字符
- javascript - 如何在茉莉花单元测试中触发元素的keydown
- javascript - 内联 css 样式使用 javascript 填充 2 层 SVG 图像的所有路径
- javascript - 弹出模式最终只是网站上的“div”
- java - Keycloak、spring 和 /sso/login URL 设置
- css - 如何防止浏览器向按钮添加对比度?
- python - 如何在 Dialogflow CX 中使用 webhook 从一个页面转换到另一个页面