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

Vue 3与JavaScript中如何避免随机索引连续重复?

解决随机索引连续重复的问题

首先纠正原代码里的两个关键问题:

  1. 过滤逻辑错误:随机排序后的数组中,元素的id和索引没有对应关系,用index + 1匹配id会导致选中的元素和预期的随机项不一致。
  2. 随机索引重复:每次独立生成索引,没有排除上一次的结果,因此可能连续选中同一个元素。

以下是两种针对性解决方案:

方案一:彻底避免重复(遍历随机排序后的数组)

既然已经对数组做了随机排序,直接按顺序遍历这个随机数组即可,每个元素只会被选中一次,完全解决重复问题,同时修正逻辑错误。

修改后的spin函数:

const slots = ref([])

const names = ref([
  { name: 'Leslie', id: 1 },
  { name: 'Ron', id: 2 },
  { name: 'April', id: 3 },
  { name: 'Andy', id: 4 },
  { name: 'Tom', id: 5 },
  { name: 'Jerry', id: 6 },
])

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const spin = async () => {
  // 复制原数组并随机排序,避免修改原数组顺序
  const shuffledList = [...names.value].sort(() => Math.random() - 0.5);
  
  for (let i = 0; i < shuffledList.length; i++) {
    await sleep(100);
    // 直接取当前索引的元素,保持数组格式匹配slots的ref类型
    slots.value = [shuffledList[i]];
  }
}

方案二:允许重复但禁止连续重复

如果需求允许元素重复出现,但不能连续两次选中同一个,可记录上一次的索引,生成新索引时排除上一次的结果:

修改后的spin函数:

const slots = ref([])

const names = ref([
  { name: 'Leslie', id: 1 },
  { name: 'Ron', id: 2 },
  { name: 'April', id: 3 },
  { name: 'Andy', id: 4 },
  { name: 'Tom', id: 5 },
  { name: 'Jerry', id: 6 },
])

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const spin = async () => {
  const list = [...names.value];
  let lastIndex = -1; // 初始化上次索引为无效值
  
  for (let i = 0; i < list.length; i++) {
    let index;
    // 循环生成索引,直到和上次不同
    do {
      index = Math.floor(Math.random() * list.length);
    } while (index === lastIndex);
    
    lastIndex = index; // 更新上次索引记录
    await sleep(100);
    slots.value = [list[index]]; // 直接取对应元素,修正原逻辑错误
  }
}

额外优化

原代码中未使用的newArray变量可直接删除,减少冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:09:24