Generate random list of words with JS

2019-07-27 06:37发布

问题:

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.

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>

回答1:

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

  1. randomly shuffle your array,
  2. pick up the N first items of the suffled array

Example code :

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

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

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