我在我的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