Created
July 14, 2017 06:51
-
-
Save xiaojue/409ec9bb428d7c0c465dd393ebf41df2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getRandom(n, arr, ret) { | |
ret = ret || []; | |
var randomNum = parseInt(Math.random() * (arr.length - 1), 10); | |
if (ret.indexOf(randomNum) === -1) { | |
ret.push(randomNum); | |
} else { | |
getRandom(n, arr, ret); | |
} | |
return ret.length === n ? ret : getRandom(n, arr, ret); | |
} | |
function getClassmate(random, classmates) { | |
return random.map(function(item) { | |
return classmates[item]; | |
}); | |
} | |
function filterClassmate(target, classmates) { | |
var less = []; | |
for (var i = 0; i < classmates.length; i++) { | |
var item = classmates[i]; | |
if (target.indexOf(item) === -1) { | |
less.push(item); | |
} else { | |
var index = target.indexOf(item); | |
target.splice(index, 1); | |
} | |
} | |
return less; | |
} | |
var key = 'classmates'; | |
var n = 5; | |
function getData() { | |
return JSON.parse(localStorage.getItem(key)) || ['冷安娜', '朱明萃', '郭华', '唐玉红', '仵恩东', '邱文瑾', '王俊', '王珂', '胡莉莉', '杨荣杰', '徐文枝', '戚文娜', '徐宝龙', '董祥恒', '李玲', '蔡利霞', '孙锐', '唐胜蓝', '朱钰', '王家宇', '郑丽平', '吴美莲', '雷湾', '张梦雪', '祁文', '李奎', '王梦嫦', '武茵倩', '毕石磊', '夏凯', '冷安娜', '朱明萃', '郭华', '唐玉红', '仵恩东', '邱文瑾', '王俊', '王珂', '胡莉莉', '杨荣杰', '徐文枝', '戚文娜', '徐宝龙', '董祥恒', '李玲', '蔡利霞', '孙锐', '唐胜蓝', '朱钰', '王家宇', '郑丽平', '吴美莲', '雷湾', '张梦雪', '祁文', '李奎', '王梦嫦', '武茵倩', '毕石磊', '夏凯']; | |
} | |
function saveData(data) { | |
localStorage.setItem("classmates", JSON.stringify(data)); | |
} | |
function main() { | |
var classmates = getData(); | |
if (n > classmates.length) { | |
console.log('剩下的人不够抽了'); | |
return; | |
} | |
var randomArr = getRandom(n, classmates); | |
var targetArr = getClassmate(randomArr, classmates); | |
console.log(targetArr.join(',') + '中奖啦'); | |
var lessClassmate = filterClassmate(targetArr, classmates); | |
saveData(lessClassmate); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment