我是一名从事Hangman游戏工作的Javascript学生。我的循环显示密码的正确破折号码是不起作用的。它每次只显示一个短划线。 感谢帮助。谢谢。
$(document).ready(function(e) {
// array of letters to choose
var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Z"];
$("#lettersRemaining").html(alphabet);
$("#newGame").click(function() { // when user clicks on Start New Game button...
// array of words
var wordCollection = ["mansion", "statue", "gorilla", "notebook", "smartphone", "illustration", "photo", "elegant", "arborist", "keyboard", "calendar", "capital", "textbook", "horrible", "library"];
// randomly select a word from the wordCollection array
var theWord = wordCollection[Math.floor(Math.random()*wordCollection.length)];
console.log("theWord is ....");
console.log(theWord);
// Get index location of the word randomly selected above -- Not sure I even need index..??
var theWordIndex = wordCollection.indexOf(theWord);
console.log("theWordIndex is ....");
console.log(theWordIndex);
// Get number of characters in word randomly selected above
var theWordLength = theWord.length;
console.log("theWordLength is ....");
console.log(theWordLength);
// display a dash equal to the theWordLength
for (var i = theWordLength; i > 0; i--)
{
$("#dashes").html(" - ");
}
答案 0 :(得分:1)
问题在于:
$("#dashes").html(" - ");
您在每次迭代时都会覆盖#dashes
的内部HTML。你需要的是将当前内容与新破折号“连接”(将两个字符串组合在一起)。
在更实际的方面,DOM访问对性能非常有害。你通常不应该把它们放在循环中。最佳实践是在执行之前计算所有DOM更改。在您的情况下,我会准备一个dashes
变量,然后在循环执行完毕后设置#dashes
的内容。
帮助您入门的一些有用资源:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat