JavaScript中如何拼接一个数组并给每个数组索引添加随机数

How to splice an array and add random numbers to each array index in JavaScript

我正在尝试在 JavaScript 和 Vue.js 中构建一个老虎机,每个数组的索引返回一个随机数。对于这个项目,我使用 for 循环遍历在 [1, 1, 1] 处初始化的槽数组,并使用 indexOf 方法来定位每个槽数组项的索引。然后,我还循环遍历一个随机数数组,然后使用拼接方法定位每个插槽数组项的索引,从该索引中删除 1 个元素,并将给定索引处的项替换为随机数。但是,我的 slots.value.splice(index, 1, randomNum[r]) 设置似乎是在 index 处删除 1 个元素并将该元素替换为 randomNum 数组的最后一个元素。我的意图是用 randomNum 数组中不同的随机数替换 slots.value 每个索引处的元素。我该怎么做呢?

这是我的代码:

<template>
  <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
    <div class="px-4 py-6 sm:px-0">
      <div  class="grid grid-cols-3 items-center py-16">
        <div v-for="slot in slots" :key="slot.id" class="w-96 h-96">
          <div class="w-full h-full rounded-md shadow-lg border-solid border-2 border-sky-500">
            <p class="text-9xl mt-28">{{ slot }}</p>
          </div>
        </div>
      </div>

      <div class="flex justify-center">
        <button @click="spin">
          Spin
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "@vue/reactivity";

const slots = ref([1, 1, 1])

const spin = () => {
  const randomNumOne = Math.floor(Math.random() * (10 - 0) + 0)
  const randomNumTwo = Math.floor(Math.random() * (10 - 0) + 0)
  const randomNumThree = Math.floor(Math.random() * (10 - 0) + 0)

  const randomNum = [randomNumOne, randomNumTwo, randomNumThree]

  for (let i = 0; i < slots.value.length; i++) {
    for (let r = 0; r < randomNum.length; r++) {
      const index = slots.value.indexOf(slots.value[i])
      console.log(randomNum[r])
      if (index > -1) {
        // remove 1 element at each index and replace each with random numbers
        slots.value.splice(index, 1, randomNum[r])
      }
    }  
  }
}
</script>

这对你有用吗?

const slots = [1, 1, 1]

const spin = () => {
  const randomNumOne = Math.floor(Math.random() * (10 - 0) + 0);
  const randomNumTwo = Math.floor(Math.random() * (10 - 0) + 0);
  const randomNumThree = Math.floor(Math.random() * (10 - 0) + 0);

  const randomNum = [randomNumOne, randomNumTwo, randomNumThree];

  for (let i = 0; i < slots.length; i++) {
    const index = Math.floor(Math.random() * randomNum.length);
    slots[i] = randomNum.splice(index, 1)[0];
  }
}

spin();
console.log(slots);

对于 slots 数组的每个元素,我们随机取一个 randomNum 元素,将其删除并将其分配给 slots 的当前索引。

请注意,您可以在最后的 slots 中多次出现相同的数字,因为 randomNumOnerandomNumTworandomNumThree 的生成不会阻止多次生成相同的数字。