You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按1→3→2循环规则获取指定数组中的元素?

实现按指定序列循环遍历路由数组

核心思路

先将路由数组转换为以id为键的映射表,实现O(1)时间复杂度的元素查找;再定义固定循环序列[1, 3, 2],通过取模运算或生成器逻辑实现序列的重复遍历。

代码实现

1. 构建路由映射表

把原始数组转成键为id的对象,避免每次查找都遍历数组:

const routes = [
  { id: 1, path: "/", element: <HomePage /> },
  { id: 2, path: "/about", element: <AboutPage /> },
  { id: 3, path: "/review", element: <ReviewPage /> },
];

// 生成id到路由对象的映射
const routeMap = routes.reduce((map, route) => {
  map[route.id] = route;
  return map;
}, {});

2. 定义循环序列

指定需要重复的id顺序:

const cycleSequence = [1, 3, 2];

3. 按索引获取对应元素

写一个函数,传入索引值即可返回对应位置的元素,通过取模运算实现循环逻辑:

function getTargetRoute(index) {
  // 计算当前在序列中的位置(取模实现循环)
  const seqPos = index % cycleSequence.length;
  const targetId = cycleSequence[seqPos];
  return routeMap[targetId];
}

// 测试示例
console.log(getTargetRoute(0)); // 第1个元素:id=1的路由
console.log(getTargetRoute(1)); // 第2个元素:id=3的路由
console.log(getTargetRoute(2)); // 第3个元素:id=2的路由
console.log(getTargetRoute(3)); // 第4个元素:回到id=1的路由,开始循环

4. 生成无限循环的迭代器(可选)

如果需要持续获取循环的元素,可以用生成器函数:

function* cycleRouteIterator() {
  while (true) {
    for (const id of cycleSequence) {
      yield routeMap[id];
    }
  }
}

// 使用迭代器
const iterator = cycleRouteIterator();
console.log(iterator.next().value); // id=1的路由
console.log(iterator.next().value); // id=3的路由
console.log(iterator.next().value); // id=2的路由
console.log(iterator.next().value); // id=1的路由,循环继续

内容的提问来源于stack exchange,提问作者Metgher Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:09:33