首页 > 解决方案 > 如何让电脑随机选词?

问题描述

我正在做类型速度测试。我想制作一个脚本来选择一个随机单词,然后在输入框中显示它。

编辑:我想要一个在我点击它时选择一个单词的数组

我不知道如何使它有所帮助将不胜感激:)

标签: javascript

解决方案


安装随机词模块:

npm install random-words

然后

var randomWords = require('random-words');
console.log(randomWords());

其中输出,例如:

scarecrow

或者,如果您在浏览器中,则可以browserify使用该模块,或使用自定义方法,例如:

function pickRandomWord() {
  var words = []
  words[ 0] = "terrorists"
  words[ 1] = "escapology"
  words[ 2] = "brightwork"
  words[ 3] = "verkrampte"
  words[ 4] = "protectrix"
  words[ 5] = "nudibranch"
  words[ 6] = "grandchild"
  words[ 7] = "newfangled"
  words[ 8] = "flugelhorn"
  words[ 9] = "mythologer"
  words[10] = "pluperfect"
  words[11] = "jellygraph"
  words[12] = "quickthorn"
  words[13] = "rottweiler"
  words[14] = "technician"
  words[15] = "cowpuncher"
  words[16] = "middlebrow"
  words[17] = "jackhammer"
  words[18] = "triphthong"
  words[19] = "wunderkind"
  words[20] = "dazzlement"
  words[21] = "jabberwock"
  words[22] = "witchcraft"
  words[23] = "pawnbroker"
  words[24] = "thumbprint"
  words[25] = "motorcycle"
  words[26] = "cryptogram"
  words[27] = "torchlight"
  words[28] = "bankruptcy"

  // generate a random number between 0 and the words array length
  var index = Math.floor(Math.random() * words.length)
  // return the picked index word
  return words[index]
}

推荐阅读