[英]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
的当前索引。
请注意,由于randomNumOne
、 randomNumTwo
和randomNumThree
的生成不会阻止多次生成相同的数字,因此您可以在最终slots
中多次出现相同的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.