我在我的JavaScript类中有一个任务,这个任务提出了一个问题,我觉得我已经接近能够回答了,但只是没有完全达到目标。外星人名字发生器
让我感到困惑的一件事是为什么开发人员工具会告诉我变量“消息”为空。我无法弄清楚。在这个问题之前的任务(这是类似的问题),我已经能够轻松得到。我可能会过度思考。
问题: “创建将生成一组的五胡乱申请‘外国人的名字’单击按钮时,这些外国人名必须在其中至少一个元音,应该有两个重复的字符某处英寸名称,示例名称包括:'llag','Uffrd'和'Dxxi'
这些名称应在DOM上向用户显示,并在随后的按钮单击时用新名称替换。
我的代码(已摆弄周围用它颇有几分粘贴之前没有检查,所以请原谅我,如果这是很难浏览。让我知道你将如何去用JavaScript解决这个。
//declares and assaigns the message (text where names will be printed)
var message = document.querySelector("#message");
//declares the array and gives it 5 spots for names
var nameArray = ["", "", "", "", ""];
// declares the name generating function
function rando() {
//declares assigns name as empty for now
var name = [];
//randomizes length of the name
var namelength = Math.round(Math.random() * 7) + 4;
//declaring a vowel count
var vowelCount = 0;
//for loop to store each name into the array
for (var i = 0; i < 5; i++) {
//for loop to decide the letters for each
for (var i = 0; i < namelength; i++) {
//declares boolean variable that stores whether or not the current character is a vowel using the created is Vowel() function
var wasVowel = isVowel(name[i]);
//if the last character was a vowel
if (wasVowel) {
//counts vowels
vowelCount++;
//while loop
while (isVowel(name[i])) {
//declares the variable and assigns it to a random number between 0 and 25
var randomCharacterIndex = Math.round(Math.random() * 25);
//updates the current character based on the random variable equal to or above the unicode 97 ("a")
name[i] = String.fromCharCode(97 + randomCharacterIndex);
}
//if the previous character was not a vowel
} else {
//while loop
while (isVowel(name[i]) == false) {
//declares variable and assigns it to random number between 0 and 25
var randomCharacterIndex = Math.round(Math.random() * 25);
//updates the current character based on the random variable equal to or above the unicode 97 ("a")
name[i] = String.fromCharCode(97 + randomCharacterIndex);
}
}
//adds each letter to the name
name += name[i];
}
//making the first letterz
name[0].toUpperCase();
//adds each name to the array
nameArray[i] = name.join("");
//name is reset to null for the next name loop
name = [];
}
//prints the names onto the DOM
message.innerHTML = nameArray.join(", ");
}
function isVowel(character) {
if (character == "a" || character == "e" || character == "i" || character == "o" || character == "u") {
return true;
} else {
//this is the 'default'
return false;
}
}
<button onclick="rando()">Random Names</button>
<div id="message"></div>
欢迎来到Stack Overflow。请更新您的问题以包含代码的工作演示,以便我们看到问题。请参阅[如何创建最小,完整和可验证的示例](https://stackoverflow.com/help/mcve)和 [如何创建可运行的代码段](https://stackoverflow.blog/2014/09/16/introduction-runnable-javascript-css-and-html-code-snippets /) – FluffyKitten
它是空的,因为你必须在这里HTML。你的HTML在哪里?另外,在你的'isVowel'函数中使用or运算符'||'并在一个'if'语句中完成。或者更好的是,使用'some'。 – jmargolisvt
嘿,我添加了我的HTML到我发布的答案。对于那个很抱歉。谢谢。我将缩短isVowel函数并使用||而不是“或”。我不知道为什么我在这个问题上遇到这么多麻烦 – jtsports1217