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/


相关推荐
小李子呢021121 小时前
前端八股Vue---Vue2和Vue3的区别,set up的用法
前端·javascript·vue.js
m0_6470579621 小时前
Harness Engineering 实践指南
前端
邂逅星河浪漫1 天前
【银行内网开发-管理端】Vue管理端+Auth后台开发+Nginx配置+Linux部署(详细解析)
linux·javascript·css·vue.js·nginx·html·前后端联调
JJay.1 天前
Android BLE 稳定连接的关键,不是扫描,而是 GATT 操作队列
android·服务器·前端
一 乐1 天前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·电影院购票管理管理系统
星空椰1 天前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript
奔跑的呱呱牛1 天前
@giszhc/vue-page-motion:Vue3 路由动画怎么做才“丝滑”?(附在线示例)
前端·javascript·vue.js
ThridTianFuStreet小貂蝉1 天前
面试题4:讲一讲HTML5、CSS3新特性
前端·css3·html5
慕斯fuafua1 天前
CSS——浮动
前端·css
gCode Teacher 格码致知1 天前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript