簡體   English   中英

如何拼接一個數組並在 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的當前索引。

請注意,由於randomNumOnerandomNumTworandomNumThree的生成不會阻止多次生成相同的數字,因此您可以在最終slots中多次出現相同的數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM