如何修改JavaScript随机取词代码实现随机抽取2个单词组成词组
你可以根据是否允许词组内出现重复单词,选择对应的调整方案:
方案1:允许词组内出现重复单词(实现最简单)
直接调用两次原有随机单词生成函数,拼接为词组即可,代码如下:
let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"]; let getRandomWord = function () { return words[Math.floor(Math.random() * words.length)]; }; // 拼接词组,中间可按需替换为横杠、下划线等自定义连接符 let phrase = `${getRandomWord()} ${getRandomWord()}`; console.log(phrase); document.getElementById("word").textContent = phrase;
方案2:词组内两个单词不允许重复(更符合常规使用需求)
通过临时拷贝单词数组、删除已抽取单词的方式,保证两次抽到的单词唯一,代码如下:
let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"]; let getUniqueRandomPhrase = function () { // 拷贝原数组避免修改原始单词库 const tempWordList = [...words]; // 抽取第一个单词 const firstIndex = Math.floor(Math.random() * tempWordList.length); const firstWord = tempWordList.splice(firstIndex, 1)[0]; // 从剩余单词中抽取第二个 const secondIndex = Math.floor(Math.random() * tempWordList.length); const secondWord = tempWordList[secondIndex]; // 自定义拼接格式,此处用空格分隔 return `${firstWord} ${secondWord}`; }; let phrase = getUniqueRandomPhrase(); console.log(phrase); document.getElementById("word").textContent = phrase;
如果需要用其他符号连接两个单词,只需修改模板字符串中两个变量中间的字符即可,比如把空格换成-即可生成monitor-program格式的词组。
内容的提问来源于stack exchange,提问作者DangolBeeker
相关产品推荐
相关产品推荐

