我没有找到任何解决方案。到处只显示数组的第一个和最后一个元素。
假设我有一个数组
[
{ name: "Hero", Id: "hero" },
{ name: "About", Id: "about" },
{ name: "Proccess", Id: "process" },
{ name: "Mission", Id: "mission" },
{ name: "Skill", Id: "skill" },
{ name: "Service", Id: "service" },
{ name: "Work", Id: "work" },
{ name: "Contact", Id: "contact" },
]
这里每个对象都有一个 Id。假设事件 ID 是 service
。当我的事件 ID 是 service
时,我必须找到它的上一个和下一个 Id(上一个 skill
,下一个 work
)。在这里,我必须根据事件 ID 查找上一个和下一个对象。此处 Active Id 可以更改。当 Active Id 更改时,我必须找到上一个和下一个对象 ID 的更改。
我想我可以解答这个问题了。对我来说这很困难。请帮助我。
最佳答案
您可以使用array.findIndex获取当前索引,然后使用 -
和 +
分别获取上一个和下一个索引。您还需要考虑越界索引。如果索引超出范围,我的函数将返回 undefined
。
const arr = [
{ name: "Hero", Id: "hero" },
{ name: "About", Id: "about" },
{ name: "Proccess", Id: "process" },
{ name: "Mission", Id: "mission" },
{ name: "Skill", Id: "skill" },
{ name: "Service", Id: "service" },
{ name: "Work", Id: "work" },
{ name: "Contact", Id: "contact" },
]
const getPrevAndNext = (activeID) => {
const index = arr.findIndex((a) => a.Id === activeID)
if (index === -1) {
return undefined
}
const prev = arr[index - 1]
if (!prev) {
return undefined
}
const next = arr[index + 1]
if (!next) {
return undefined
}
return [prev, next]
}
console.log(getPrevAndNext('service'))
关于javascript - 如何查找事件对象的数组的上一个和下一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70563387/