如何用JavaScript从纽约时报API仅展示前4篇文章?
解决方案:仅显示纽约时报API返回的前4篇文章
很简单,你现在的代码用forEach遍历了所有返回的文章,所以会渲染全部20篇。这里有两种直接的修改方式,帮你只展示前4篇:
方法一:截取前4篇文章再遍历
直接用数组的slice(0,4)方法截取前4个元素,然后遍历这个子数组就行,代码改动很小:
let html = []; fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=...') .then((resp) => resp.json()) .then(function(data) { // 截取数组的前4个元素 const topFourArticles = data.results.slice(0, 4); topFourArticles.forEach(res => { html.push(`<h1>${res.title}</h1>`); // 把URL改成可点击的链接,提升体验 html.push(`<p><a href="${res.url}" target="_blank">查看原文</a></p>`); html.push(`<p>${res.abstract}</p>`); html.push(`<p>发布日期: ${res.published_date}</p>`); // 加个判断避免多媒体元素不存在时报错 if (res.multimedia && res.multimedia[4]) { html.push(`<img src="${res.multimedia[4].url}" alt="${res.title}" style="max-width:100%;" />`); } }) document.getElementById("res").innerHTML = html.join(""); }) // 加上错误处理,方便排查问题 .catch(err => console.error('获取新闻数据失败:', err));
slice(0,4)的作用是从数组起始位置(索引0)截取到索引3(第二个参数是结束位置,不包含),刚好得到前4篇文章。
方法二:遍历的时候判断索引
如果你不想创建新数组,也可以在forEach里通过索引判断,只处理前4个元素:
let html = []; fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=...') .then((resp) => resp.json()) .then(function(data) { data.results.forEach((res, index) => { // 只处理索引小于4的元素(也就是前4篇) if (index < 4) { html.push(`<h1>${res.title}</h1>`); html.push(`<p><a href="${res.url}" target="_blank">查看原文</a></p>`); html.push(`<p>${res.abstract}</p>`); html.push(`<p>发布日期: ${res.published_date}</p>`); if (res.multimedia && res.multimedia[4]) { html.push(`<img src="${res.multimedia[4].url}" alt="${res.title}" style="max-width:100%;" />`); } } }) document.getElementById("res").innerHTML = html.join(""); }) .catch(err => console.error('获取新闻数据失败:', err));
两种方法都能达到目的,选你觉得顺手的就行。
额外优化:支持“显示更多”功能
如果之后你想加个按钮让用户查看剩下的文章,可以把所有文章数据存起来,初始只渲染前4篇,点击按钮再渲染全部:
let allArticles = []; const resultContainer = document.getElementById("res"); fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=...') .then((resp) => resp.json()) .then(function(data) { allArticles = data.results; // 初始渲染前4篇 renderArticles(4); }) .catch(err => console.error('获取新闻数据失败:', err)); // 封装渲染函数,方便复用 function renderArticles(count) { const articlesToShow = allArticles.slice(0, count); let html = []; articlesToShow.forEach(res => { html.push(`<div style="margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 1px solid #eee;">`); html.push(`<h2>${res.title}</h2>`); html.push(`<p><a href="${res.url}" target="_blank" rel="noopener noreferrer">查看原文</a></p>`); html.push(`<p>${res.abstract}</p>`); html.push(`<p style="color: #666; font-size: 0.9rem;">发布日期: ${res.published_date}</p>`); if (res.multimedia && res.multimedia[4]) { html.push(`<img src="${res.multimedia[4].url}" alt="${res.title}" style="max-width:100%; border-radius: 4px;" />`); } html.push(`</div>`); }); resultContainer.innerHTML = html.join(""); // 如果还有未显示的文章,添加显示更多按钮 if (allArticles.length > count) { const showMoreBtn = document.createElement('button'); showMoreBtn.textContent = '显示全部新闻'; showMoreBtn.style = 'padding: 0.5rem 1rem; background: #000; color: white; border: none; border-radius: 4px; cursor: pointer;'; showMoreBtn.onclick = () => { renderArticles(allArticles.length); }; resultContainer.appendChild(showMoreBtn); } }
这个版本还加了点简单的样式,让文章列表看起来更整洁,同时处理了链接的rel属性提升安全性。
内容的提问来源于stack exchange,提问作者SK1dev
相关产品推荐
相关产品推荐

