var secretWord = [];
var underScoreWord = [];
// var guesses = [];
var wordLetter = false;
var city = ["Paris", "Wellington", "Hanoi", "Perth", "Marseille", "London", "Ottawa", "Zurich", "Boston", "Tokyo", "Detroit"];
// console.log(city);
// Pick random word from the team array and push the result to an empty array.
// FUNCTION 1 pick random city
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord.push(randomCity);
return randomCity;
}
var cityPicked = pickRandomCity();
// Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log(secretWord);
console.log(underScoreWord);
// Check for letters
//listen for key press and check to see if its a match
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
for (var j = 0; j < cityPicked.length; j++) {
if (userGuess === cityPicked[j]) {
wordLetter = true;
}
if (wordLetter) {
underScoreWord.push(userGuess);
}
}
console.log(wordLetter);
}
在onkeyup函数内部,我试图将结果(按下的键)推入underScoreWord数组。当我键入正确的键时,它会将wordLetter布尔值转换为true,但我不知道如何将其推入显示在单词中,因此它显示如下_ _ N _ _ _
我想我很近,但是我可能又相距甚远。有提示吗?
答案 0 :(得分:1)
您要通过按_
数组中匹配的单词按下键来填充underScoreWord
值
示例:
如果东京被选为居住城市,
它将[ "_", "_", "_", "_" ]
存储在underScoreWord
现在,如果按T
,它将填充到[ "T", "_", "_", "_" ]
在使用后按o
,它将填充到[ "T", "o", "_", "o" ]
问题:
secretWord
是数组,但以1个长度存储整个单词- 仅在
underScoreWord
中填充正确拼写匹配的相同索引
请检查以下解决方案:
var secretWord = [];
var underScoreWord = [];
var guesses = [];
var wordLetter = false;
var city = ["Paris", "Wellington", "Hanoi", "Perth", "Marseille", "London", "Ottawa", "Zurich", "Boston", "Tokyo", "Detroit"];
// Pick random word from the team array and push the result to an empty array.
// FUNCTION 1 pick random city
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
// Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log('secretWord : ' + secretWord);
console.log('underScoreWord : ' + underScoreWord);
console.log('------------------');
console.log('cityPicked : ' + cityPicked);
// Check for letters
//listen for key press and check to see if its a match
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
for (var j = 0; j < secretWord.length; j++) {
if (userGuess === secretWord[j]) {
wordLetter = true;
underScoreWord[j]= userGuess;
}
}
console.log(underScoreWord);
}
答案 1 :(得分:0)
尝试这个
替换此
underScoreWord.push(userGuess);
为此
underScoreWord[j] = userGuess
答案 2 :(得分:0)
您无需将字母推到underScoreWord
上。只需将相应的下划线替换为字母即可。
for (var j = 0; j < cityPicked.length; j++) {
if (userGuess == cityPicked[j]) {
underScoreWord[j] = userGuess;
}
}