我正在制作一个单词生成器。您输入您选择的十个字符串。它应该输出一个随机选择的字符串。它会输出一个随机选择的数字,但它不应该输出。它应该输出用户输入的字符串。我没有收到错误。
如何让它显示用户输入?
有什么建议吗?最近几天我一直被这个问题困扰。
function randomWordGenerator() {
// Define the variables
var userInput = [];
var answer = [], range = 1;
var array = [];
var set = [];
// Prompt for String
for(var index = 0; index < 10; index++) {
userInput = prompt("Please enter string." + (index + 1));
document.write("You entered: " + userInput + "\n");
}
// Generator
for(var i = 0; i < range; i++) {
answer[i] = Math.floor((Math.random() * 10) + 1);
}
// Generator Pick Display
document.write("The generator choose: " + answer);
}
randomWordGenerator();
最佳答案
您必须将用户输入保存到数组中。您在代码中所做的就是始终覆盖 userInput
,即只有用户输入的最后一个单词保存在该变量中。然后生成一些随机数,将它们全部插入一个数组并将其输出给用户。其工作原理如下:
function randomWordGenerator() {
// Define the variables
var array = [];
// Prompt for String
for (var index = 0; index < 10; index++) {
var userInput = prompt("Please enter string." + (index + 1));
array.push(userInput);
document.write("You entered: " + userInput + "\n");
}
// select random number from array in which you stored the words
var answer = array[Math.floor(Math.random() * array.length)];
// Generator Pick Display
document.write("The generator choose: " + answer);
}
randomWordGenerator();
关于JavaScript 单词生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293555/