我正在用 JS/jQuery 创建一个 Hangman 游戏(有一些改动)。我已经弄清楚如何根据用户输入(当他们猜测字母时)来识别正在猜测的单词数组的索引。但是,我无法弄清楚如何获取该索引并将空白(underscoreArray)替换为同一索引处的用户输入的值。
我尝试使用条件(在 JS 代码末尾)来执行此操作,但我不确定如何实现此操作。
如果猜测正确,此条件应将 html 从(例如,如果单词是“drag”并且用户猜测“d”)“_ _ _ _”更改为“d __ _ _”。
这是fiddle这是 JS:
$(document).ready(function() {
var words = ["shade", "she mail", "queen"];
var usedLetters = [];
var wrongLetters = [];
$('.play').click(function() {
var word = words[Math.floor(Math.random() * words.length)];
var wordLength = word.length;
var underscores = "";
for (i = 0; i < wordLength; i++) {
underscores = underscores + "_ ";
}
$('.btn-default').on('click', function() {
var guess = $(this).text();
if (jQuery.inArray(guess, usedLetters) === -1) {
usedLetters.push(guess);
$('.used').html('<p class="used">Letters used:</p><span>' + usedLetters + '</span>');
} else {
alert("You already guessed \"" + guess + "\"!");
}
/*Find out if guess = an index of word, and if it does replce the underscore index with the guess*/
var find = word.indexOf(guess);
var wordArray = [word];
//loop through wordArray and where wordArray === find replace same index of underscores with guess.
for (i = 0; i < wordArray.length; i++) {
var underscoresArray = [underscores];
var index = wordArray.indexOf(guess);
if (index !== -1) {
underscoresArray[index] = guess;
$('#words').after(underscoresArray).toString();
};
}
});
});
});
最佳答案
有几个问题:
- 如@Glubus pointed out ,
[word]
不创建字符数组。使用word.split('')
。 - 您将
下划线
字符串设置为包含空格,使其长度是word
的两倍,因此index
需要为乘以二进行补偿 - 您无法捕获猜测字母的每个实例,因为
indexOf
仅返回第一个
这应该更接近:
var wordArray = word.split('');
var underscoresArray = underscores.split('');
for (var i = 0; i < wordArray.length; i++) {
// Catch every letter, eg. the "p"s in "popcorn"
if (wordArray[i] == guess) {
// Underscored indices are twice the word indices
// "popcorn" -> "p _ p _ _ _ _"
underscoresArray[i * 2] = guess;
};
}
// Only need to do this once after all changes are made
underscores = underscoresArray.join(''); // Collapse back to string
$('#words').after(underscores);
console.log(underscores);
关于javascript - 循环遍历数组以查找用户输入的索引,然后替换另一个数组的相同索引处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35581860/