如何使用JavaScript过滤数组并获取限定数量的目标数据
解决方案
你需要先定位到匹配项在数组中的索引,再通过索引提取后续2个元素即可,修改后的代码如下:
const _ = require('lodash'); // 此处默认你的blogData数组是按期望的先后顺序存储 app.get("/:id", (req, res) => { const requestParams = _.lowerCase(req.params.id); // 用findIndex直接获取匹配项的数组索引 const matchIndex = blogData.findIndex(post => _.lowerCase(post.heading) === requestParams); // 处理没有匹配到的场景,避免程序报错 if (matchIndex === -1) { return res.status(404).send('未找到对应文章'); } const currentPost = blogData[matchIndex]; // 提取紧随其后的2个元素,slice自动处理边界不足的情况,不够2个就返回实际存在的数量 const nextPosts = blogData.slice(matchIndex + 1, matchIndex + 3); // 把当前文章和后续2篇一起传到EJS模板 res.render("blogfullDetail", { date: currentPost.date, heading: currentPost.heading, subheading: currentPost.subheading, discription: currentPost.discription, discription2: currentPost.discription2, author: currentPost.author, authorImage: currentPost.authorImage, mainImg: currentPost.mainImg, // 新增后续文章变量,模板里直接遍历nextTwoPosts即可渲染 nextTwoPosts: nextPosts }); });
代码说明
- 替换原有的
forEach遍历为findIndex,直接获取匹配项的索引位置,匹配失败返回-1,可以直接用来做404判断,也避免了原代码中匹配成功后仍继续遍历、多次调用res.render报错的问题 - 使用数组的
slice方法提取后续元素,slice(start, end)是左闭右开规则,所以写matchIndex+1到matchIndex+3刚好取2个元素,就算匹配项在数组末尾、后面不足2个,slice也不会报错,会返回所有存在的后续元素 - 你只需要在EJS模板
blogfullDetail.ejs里遍历nextTwoPosts变量,就能渲染紧随的2篇文章内容
数据结构说明
你提供的数据结构截图如下:
只要你的blogData数组是按你需要的展示顺序存储的,上述代码就可以正常运行。
内容的提问来源于stack exchange,提问作者private name
相关产品推荐
相关产品推荐

