如何选择要生成多少个随机字符串?



我正在尝试创建一个随机名称生成器。如何选择要生成的字符串数量,而无需复制和粘贴如此多的代码副本?有没有办法有一个输入框,我可以在其中输入一个数字,它会生成该金额?

function generator() {
var planets = ["mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"];

var planets = planets[Math.floor(Math.random() * planets.length)] + " " 
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
+ planets[Math.floor(Math.random() * planets.length)] + " "
;

if (document.getElementById("planets")) {
document.getElementById("placeholder").removeChild(document.getElementById("planets"));
}

var element = document.createElement("div");
element.setAttribute("id", "planets");
element.appendChild(document.createTextNode(planets));
document.getElementById("placeholder").appendChild(element);
}   

我假设您不仅要选择随机名称,而且该随机选择中没有重复项。

最简单的方法是使用随机洗牌数组的函数。您可以从此处"借出"实现。

注意:似乎没有充分的理由删除并重新创建文档中的植物元素。只需重复使用它。

以下是与您的行星阵列的简单集成以及用于指定数字的输入:

let planets = ["mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"];
let button = document.querySelector("#generate");
let input = document.querySelector("#num");
let output = document.querySelector("#planets");
button.addEventListener("click", generate);
function generate() {
// Shuffle the planets randomly
shuffle(planets);
// Select only the number of planets that the user wants
let selected = planets.slice(0, +input.value);
// output the result, space-separated
output.textContent = selected.join(" ");
}
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
number of planets: <input type="number" id="num" size="3" value="4">
<button id="generate">Generate</button><br>
<div id="planets"></div>

最新更新