简体   繁体   English

如何防止在 Vue 3 和 JavaScript 中重复随机数

[英]How to prevent repeating random numbers in Vue 3 and JavaScript

I am attempting to build a function that loops through a series of array objects containing names and ids after the array objects have been randomized, then returns a single filtered item to slots.value .我正在尝试构建一个 function ,它在数组对象被随机化后循环一系列包含名称和 ID 的数组对象,然后将单个过滤项返回到slots.value So far, my spin function works in terms of looping through the randomized objects.到目前为止,我的自旋 function 的工作原理是循环遍历随机对象。 However, the line const index = Math.floor(Math.random() * list.length) occasionally returns the same index number twice in a row.但是, const index = Math.floor(Math.random() * list.length)行偶尔会连续两次返回相同的索引号。 I wish to prevent the random index function from returning the same index number twice in a row.我希望防止随机索引 function 连续两次返回相同的索引号。 How can I do this?我怎样才能做到这一点?

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.sort(() => Math.random() - 0.5)
  const newArray = []

  for (let i = 0; i < list.length; i++) {
    const index = Math.floor(Math.random() * list.length)
    await sleep(100)
    slots.value = list.filter(r => r.id === (index + 1))
  }
}

One solution is to re-generate the index if the new value matches the previous one:一种解决方案是,如果新值与前一个值匹配,则重新生成索引:

let prevIndex = null
const generateRandIndex = max => {
  let index
  do {
    index = Math.floor(Math.random() * max)
  } while (index === prevIndex)
  prevIndex = index
  return index
}

const spin = async () => {
  ⋮
  for (let i = 0; i < list.length; i++) {
    const index = generateRandIndex(list.length)
    ⋮
  }
}

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM