javascript - 如何查找事件对象的数组的上一个和下一个对象?

标签 javascript arrays

我没有找到任何解决方案。到处只显示数组的第一个和最后一个元素。

假设我有一个数组

[
    { 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/

相关文章:

java - Web界面如何从服务器获取数据?

javascript - for 循环中的数组(使用 jQuery)

arrays - 在 Swift 中从 csv 文件读取数据并将数据转换为多维数组

arrays - 查找需要从数组中删除的元素,使得 2*min>max

java - A[j] = 2∗A[i] in list with better than O(n^2) runtime

javascript - 箭头主体周围有意外的 block 语句?为什么我不能回来?

javascript - ExtJS - 表单失败消息框

C编译器警告: assignment from incompatible pointer type

javascript - 如何编写接受参数的 NectarJS 程序?

javascript - 对于 IE 中的 ajax 内容,onload 触发过早