用JS生成随机单词列表
我试图构建一个随机的JS单词列表生成器,但我在这里的代码只生成一个单词。实际上,我希望它能够从之前给出的列表中生成30个单词的列表,它可以是60个单词列表或700个单词,但结果应该总是30个,没有重复的单词,但我不知道如何实现这个目标。用JS生成随机单词列表
另外,我想观众介绍自己的单词列表,然后点击“生成字的新列表”,然后页面会随机给他们的30个字有不同的顺序列表,他们每次点击按钮。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title></title>
<style type="text/css">
form {
float:left;
padding:20px 20px 10px;
border:1px solid #999;
}
label {
float:left;
width:100px;
line-height:22px;
margin-bottom:10px;
font-size:12px;
}
input {
margin-bottom:10px;
}
</style>
<script type="text/javascript">
function init(){
words0=['art','car','bus','earth','camera','phone','sun','light','number',];
df=document.forms[0];
df.reset();
df[1].onclick=function() {
rnd0=Math.floor(Math.random()*words0.length);
df[0].value=words0[rnd0];
}
}
window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);
</script>
</head>
<body>
<form action="#">
<div>
<label>word one:</label><input type="text" readonly="readonly"><br>
<input type="button" value="Click here to get random words">
<input type="reset" value="Clear">
</div>
</form>
</body>
</html>
如果你想从一个数组中随机抓取的N个项目,那么这是一种经典的方式是:
- 随机洗牌的阵列,
- 回暖的N个第一项suffled阵列
示例代码:
function samples(items, number){
items.sort(function() {return 0.5 - Math.random()});
return items.slice(0, number);
}
请注意,shuffle算法可能不是最好的,它是作为一个例子提供的,如@Phylogenesis所提到的。
如果你希望避免重塑车轮,你也可以使用undercore.js例如,提供了一个sample method
这是一个[非常糟糕的洗牌算法](http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html)。使用[Fisher-Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)。 – Phylogenesis
@Phylogenesis你是对的,但它很容易理解和实施。顺便说一句,我已经添加了一个通知,告知该算法可能不是最好的;) –
顺便说一句,更好地摆脱像'words0'或''rnd0'变量rnd1'名.. –
要从一个较大的集合中挑选n个随机项目,[shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle),然后取第一个'n'项目。 – Phylogenesis
然后你必须迭代,每次检查新的随机单词是否不在你生成的单词列表中,并且这样做直到你有30个单词。类似于:do var newWord = Math.floor(Math.random()* words0.length); if(wordsArr.indexOf(newWord)=== -1){wordsArr.push(newWord); counter ++;} } while(counter user2520818