[英]Hangman game. 2 arrays. One need to update accordingly to the other one
Im building a javascript hangman game and I'm somewhat stuck at this one problem. 我正在构建一个javascript hangman游戏,而我在这个问题上有些困惑。
Lets say the word to guess is "dog". 假设要猜的单词是“狗”。 I have created an array of this word: ["d", "o", "g"];
我创建了这个单词的数组: ["d", "o", "g"];
A hint (in for of a paragraph) in the browser is displayed with an "-" for each of the letters in the chosen word. 对于所选单词中的每个字母,浏览器中的提示(段落的in)都显示有“-”。 In this scenario the hint would display ---
. 在这种情况下,提示将显示---
。
If the user is to guess a letter correctly I want the hint to display for example d--
if the letter d is correctly guessed. 如果用户是猜测正确的信我想显示例如提示d--
如果字母d被猜中。
I have created a array out of the hint and to use the dog example the array looks like this: ["-", "-", "-"];
我已经根据提示创建了一个数组,并使用dog示例,该数组如下所示: ["-", "-", "-"];
What I'm stuck with is how to update this second array with the corresponding letter at the right place. 我坚持的是如何在正确的位置用相应的字母更新第二个数组。 The array should look something like: ["d", "-", "-"];
该数组应类似于: ["d", "-", "-"];
and then I can array.join() and display the resulting string as a new hint. 然后我可以array.join()并将结果字符串显示为新提示。
Something like the below should work well. 像下面这样的东西应该可以正常工作。 Since both your answerArray
and displayArray
are the same length you can simply loop through the answerArray
, check for any matches, and push said matches to the appropriate position in displayArray
. 由于您的answerArray
和displayArray
的长度相同,因此您可以简单地循环遍历answerArray
,检查是否有任何匹配项,并将所述匹配项推入displayArray
的适当位置。
var answerArray = ["d", "o", "g"],
displayArray = ["-", "-", "-"],
length = answerArray.length,
i;
var currentGuess = prompt("Please enter a letter: ");
for (i = 0; i < length; i++) {
if(currentGuess === answerArray[i]) {
displayArray[i] = currentGuess;
}
}
You have two arrays: 您有两个数组:
var word = ["d", "o", "g"];
var guessedWord = ["-", "-", "-"];
When the letter is correct you can do: 字母正确时,您可以执行以下操作:
var idx = word.indexOf("d");
guessedWord[idx] = word[idx];
The arrays should be the same length, so you can just naively assign the value(s). 数组的长度应相同,因此您可以天真地分配值。
Really basic example. 真正的基本例子。
http://jsbin.com/qoteqakona/1/edit?js,console http://jsbin.com/qoteqakona/1/edit?js,控制台
var word = 'hello'.split('');
var blanks = word.map(function (e) {
return '-';
});
function guess(l) {
word.forEach(function (e, i) {
if (e === l) blanks[i] = word[i];
});
return blanks;
}
console.log(guess('l'));
console.log(guess('h'));
console.log(guess('i'));
In the .forEach()
callback, e
is the value of the current element, and i
is the value of the current index. 在.forEach()
回调中, e
是当前元素的值,而i
是当前索引的值。
Extra documentation: 额外文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.