用JS生成单词的随机列表 [英] Generate random list of words with JS

查看:87
本文介绍了用JS生成单词的随机列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a random JS word list generator but the code I have here just generates a single word. Actually I want it to generate a list of 30 words from a previously given list, it may be a 60 word list or 700 but the result should always be 30 with no duplicated words, but I don't know how to achieve this.

此外,我希望访问者介绍自己的单词列表,然后单击生成新单词列表",然后页面将随机化,并在每次单击时为他们提供30个单词的顺序不同的列表按钮.

Also, I would like the visitors to introduce their own list of words and then click on "generate a new list of words" and then the page will randomize and give them a list of 30 words with different order every time they click the button.

<!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个项目,经典的做法是:

If you want to grab N items randomly from an array, a classical way of doing it is to :

  1. 随机随机排列您的数组,
  2. 拿起被折叠阵列的N个头项

示例代码:

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

请注意,如@Phylogenesis所述,它只是作为示例提供了随机播放算法.

Notice that the shuffle algorithm is probably not the best one, it is provided as an example, as mentioned by @Phylogenesis.

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

If you prefer to avoid reinvent wheels, you can also use undercore.js for example, that provides a sample method

这篇关于用JS生成单词的随机列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆