Yesterday when the annual meeting to see a joke said only the annual lottery, the results of the lottery is written by the department, the CTO Field Review code.
A simple thought about the lottery implementation of the program, took more than 10 minutes to write, the main use of the knowledge of the array added to delete, as well as ES5 array of new indexof,filter methods,
In order to refresh the page can still save the winning record, with a localstorage disk.
The first is to use random numbers directly to the number, found to eliminate the winner is very troublesome, if repeated to recursive call, if the winner of too many to the last random number to get the winner of the probability is too large, so swap with two array implementation, a record has won the number, a record of the number of the winning, There is no recursive invocation if the winning one is removed from the other array.
Specifically implemented as follows:
var Start=1,end=20,luckylist=[],futurelist=[];//luckylist said the person who has won the prize, Futurelist said that the person who has not yet smoked, Start,end said the lottery is the beginning and ending number
/ First initialize the array for all personnel numbers for
(var i=start;i<=end;i++) {
futurelist.push (i);
}
If the page is refreshed, restore if
(Localstorage.getitem ("lucky")) {
Luckylist=localstorage.getitem ("lucky") from Localstoreage . Split (",");
Futurelist=futurelist.filter (function (item) {return
Luckylist.indexof (item) ==-1;
})
Console.log (futurelist)
}
//Lottery function, each run once, produces 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 ("Lottery results:", result);
}
Clear Localstorge, if you want to reset the program to perform this function, OK
() {
Localstorage.setitem ("Lucky", "");
}
Raffle ();
The above JavaScript to achieve the lottery is a simple example of a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.