【问题标题】:Generate random list of words with JS用JS生成随机单词列表
【发布时间】:2017-09-06 09:42:24
【问题描述】:

我正在尝试构建一个随机 JS 单词列表生成器,但我这里的代码只生成一个单词。实际上我希望它从之前给定的列表中生成一个包含 30 个单词的列表,它可能是一个 60 个单词的列表或 700 个但结果应该始终是 30,没有重复的单词,但我不知道如何实现这一点。

另外,我希望访问者介绍他们自己的单词列表,然后点击“生成新的单词列表”,然后页面会随机分配给他们每次点击时不同顺序的 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>

【问题讨论】:

  • 顺便说一句,最好去掉像words0rnd0rnd1这样的变量名...
  • 要从较大的集合中随机选择 n 项目,shuffle 然后选择第一个 n 项目。
  • 那么你必须迭代,每次检查新的随机词是否不在你生成的词列表中,直到你有 30 个词。类似:做{ var newWord = Math.floor(Math.random()*words0.length); if (wordsArr.indexOf(newWord) === -1) {wordsArr.push(newWord);计数器 ++;} } while (counter
  • 感谢您的快速回复,这是否意味着我必须更改所有代码?你们中的一个可以帮助我吗?也许我可以让你访问我的页面,我们可以安排一些事情,对不起我的英语不好。

标签: javascript list random


【解决方案1】:

如果你想从一个数组中随机抓取 N 个元素,一个经典的方法是:

  1. 随机洗牌,
  2. 取出打乱数组的前 N ​​项

示例代码:

function samples(items, number){
    items.sort(function() {return 0.5 - Math.random()});
    return items.slice(0, number);
}

请注意,shuffle 算法可能不是最好的算法,它是作为示例提供的,正如@Phylogenesis 所述。

如果您希望避免重新发明轮子,也可以使用 undercore.js,例如,它提供了 sample method

【讨论】:

  • @Phylogenesis 你是对的,但是它很容易理解和实现。顺便说一句,我已经添加了一条通知,通知该算法可能不是最好的;)
猜你喜欢
  • 2013-12-17
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
相关资源
最近更新 更多