ES6实现简易抽奖模块
博客主页:https://blog.csdn.net/weixin_53893220?spm=1001.2101.3001.5343
本文代码将展示用Generator实现抽奖的可控制化,用yield来控制每次的抽奖结果输出
对抽奖按钮自定义后,每次点击按钮都调用person对象的内置next方法进行数值的输出,从而达到控制抽奖的进行,而不是一次性将所有得奖人物都输出,es6的妙用
js部分代码如下:
function* chouJiang(firstPeople, SecondPeople, thirdPeople) {
let first = ['1a', '1b', '1c', '1d']
let second = ['2a', '2b', '2c', '2d', '2d', '2e', '2f']
let third = ['3a', '3b', '3c', '3d', '3e', '3f', '3g', '3h']
let count = 0
let totalSum = 6
let random
while (1) {
if (count < firstPeople) {
random = Math.floor(Math.random() * first.length)
yield first[random]
count++
first.splice(random, 1)
} else if (count < firstPeople + SecondPeople) {
random = Math.floor(Math.random() * second.length)
yield second[random]
count++
second.splice(random, 1)
} else if (count < firstPeople + SecondPeople + thirdPeople) {
random = Math.floor(Math.random() * third.length)
yield third[random]
count++
third.splice(random, 1)
} else {
return false
}
}
}
let person = chouJiang(1, 2, 3)
// console.log(person.next().value)
// console.log(person.next().value)
// console.log(person.next().value)
// console.log(person.next().value)
// console.log(person.next().value)
// console.log(person.next().value)
// console.log(person.next().value)
在这里模仿的实际抽奖,first,second,third三个数组为参与对应奖项的待定人选,
给该抽奖函数传入的参数为(1,2,3),即一等奖一名,二等奖两名,三等奖三名
html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script src="异步test.js"></script> -->
<script src="抽奖.js"></script>
<style>
button {
width: 100px;
height: 100px;
font-size: 40px;
text-align: center;
}
</style>
</head>
<body>
<button onclick="console.log(person.next().value)">抽奖</button>
<p id="demo"></p>
</body>
</html>