我正在嘗試用 JavaScript 和 Vue.js 構建一個老虎機,每個陣列的索引回傳一個亂數。對于這個專案,我使用 for 回圈遍歷初始化為 的插槽陣列[1, 1, 1],并使用 indexOf 方法來定位每個插槽陣列項的索引。然后,我還回圈遍歷一個亂數陣列,然后使用拼接方法來定位每個插槽陣列項的索引,從該索引中洗掉 1 個元素,并將該給定索引處的項替換為亂數。但是,我的slots.value.splice(index, 1, randomNum[r])設定似乎是在洗掉 1 個元素index并將該元素替換為randomNum陣列的最后一個元素。slots.value我的意圖是用陣列中不同的亂數替換每個索引處的元素randomNum。我該怎么做呢?
這是我的代碼:
<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>
uj5u.com熱心網友回復:
這對你有用嗎?
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請注意,自 生成以來,您可以在決賽中多次出現相同的數字randomNumOne,randomNumTwo并且randomNumThree不會阻止多次生成相同的數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/480691.html
標籤:javascript 数组 Vue.js Vuejs3 拼接
上一篇:無法從子組件vue3.0接收事件
下一篇:禁用vue組件互動
