Yesterday, when I was holding an annual meeting, I saw a joke about the lottery draw of Vipshop, but the prizes were won by the department that wrote the lottery procedures, and the CTO reviewed the code on site.
I briefly thought about the implementation of the lottery program and spent more than ten minutes writing it out. The main knowledge used are array addition and deletion, as well as the indexOf and filter methods added to the ES5 array.
In order to save the winning records after refreshing the page, localStorage was used to save the winning records.
At the beginning, I used random numbers to directly get the number. I found that it was very troublesome to eliminate the winners. If you repeatedly call recursively, if there are too many winners and the probability of getting the winners is too high in the end, so I used two arrays to implement it. One recorded the winning number and the other recorded the unwinned number. The winners were just eliminated from the other array, and there was no recursive call.
The specific implementation is as follows:
var start=1,end=20,luckyList=[],futureList=[];//luckyList indicates the person who has won the prize, futureList indicates the person who has not yet won the lottery, start,end indicates the start and end number of the lottery //Initialize the array of all personnel numbers first for(var i=start;i<=end;i++){futureList.push(i);}//If the page is refreshed, restore if(localStorage.getItem("lucky")){luckyList=localStorage.getItem("lucky").split(",");futureList=futureList.filter(function(item){ return luckyList.indexOf(item)==-1;})console.log(futureList)}//The lottery function, each time it runs, generates a lucky number function raffle(){var num= Math.random()*futureList.length;num=Math.floor(num);var idx=futureList.indexOf(num);var result=futureList.splice(idx,1)[0].toString();luckyList.push(result);localStorage.setItem("lucky",luckyList);console.log("lucky",result);} //Clear localstorge, if you want to reset the program to execute this function function clear(){localStorage.setItem("lucky","");}raffle();The above simple example of JavaScript implementing the lottery program is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.