Js如何实现一个抽奖程序

前言

无论是在手机 App 端,还是网页,在活动日的时候,商家都会弄些抽奖的活动,抽金币,金劵等。

纯 js 如何实现一个轻量级的抽奖程序呢?

废话不多说,直接上代码。

Vue 实现

实现原理也很简单:

  • 定义一个候选人数组 lists;

  • 通过 Math.random() 生成随机数;

  • 将生成的随机数乘以数组的最大下标值,并向下取整,获取数组的随机下标值。

  • 通过定时器实现重复循环生成候选人数组随机下标值,直到点击停止,获取中奖人对应的数组下标值。

    <template>

    抽奖名单

    • {{item}}
    <el-button type="primary" @click="handleStart">开始抽奖</el-button> <el-button type="success" @click="handleStop">停止抽奖</el-button> 抽奖结果:{{this.result}}
    </template> <script> export default { data() { return { lists: ['张三','李四','王五','小刘','罗胖','胡玲','周通','徐达','杨新'], timer: null, // 定时器 result: '', randIndex: null } },
    复制代码
      methods: {
         // 开始抽奖
         handleStart() {
            if(!this.timer) {
              // 创建定时器
              this.timer = setInterval(() => {
                  let max = this.lists.length-1;  // 最大的下标数字
                  let rand = Math.random();       // 随机数,小于0
                   // 定义一个random()函数,原理是 随机数和最大值减最小值的差相乘 最后再加上最小值
                  // Math.floor(Math.random() * (max - min)) + min
                  this.randIndex = Math.floor(rand*max)+1;  // 向下取整
                  this.result = this.lists[this.randIndex]   // 得到的结果
              },50)
            }
         },
         // 停止抽奖
         handleStop() {
           clearInterval(this.timer); // 清除定时器
           this.timer = null;
           this.result = this.lists[this.randIndex];
           this.$message({
              message: `中奖的是${this.result}`,
              type: 'success'
           });
         }
      }

    }
    </script>

    <style lang="scss" scoped> .choujiang-wrap { text-align: center; margin-top: 10px; }
    复制代码
    .choujiang-item {
      display:flex;
      justify-content: center;
    }
    
     .choujiang-item li {
       margin-right: 10px;
     }
    
     .active {
       color: red;
       font-weight: bold;
     }
    
     .btn {
       margin-top: 20px;
     }
    </style>

通过上面的代码,我们就能实现一个简易的抽奖程序。

🎁 福利时间

如果你正在备战面试或者想要学习其他知识,给大家推荐一个宝藏知识库,作者整理了一些列 Java 程序员需要掌握的核心知识,有需要的自取不谢。

知识库地址:https://farerboy.com/


相关推荐
镜宇秋霖丶1 天前
2026.5.6@霖宇博客制作中遇见的问题
前端·javascript·vue.js
计算机专业码农一枚1 天前
微信小程序 uniapp+vue高校社团管理
vue.js·微信小程序·uni-app
吴声子夜歌1 天前
Vue3——TypeScript基础
javascript·typescript
小李子呢02111 天前
前端八股Vue---Vue-router路由管理器
前端·javascript·vue.js
百锦再1 天前
Auto.js变成基础知识学习
开发语言·javascript·学习·sqlite·kotlin·android studio·数据库开发
洛_尘1 天前
Python 5:使用库
java·前端·python
Bigger1 天前
Bun 能上生产吗?我的实战结论
前端·node.js·bun
kyriewen1 天前
你的前端滤镜慢得像PPT?用Rust+WebAssembly,一秒处理4K图
前端·rust·webassembly
kyriewen111 天前
你等的Babel编译,够喝三杯咖啡了——用Rust重写的SWC,只需眨个眼
开发语言·前端·javascript·后端·性能优化·rust·前端框架
IT_陈寒1 天前
SpringBoot自动配置坑了我,原来要这样绕过去
前端·人工智能·后端