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函数内部我试图将结果(按下的键)推入theunderScoreWord数组。当我键入正确的键时它将wordLetter boolean转换为true但我无法弄清楚如何将其推送到单词内部以便显示如下_ _ N _ _ _
我想我很接近,但是我又可以离开。有小费吗?
您希望通过_
数组中匹配的单词按下来按键填充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);
}
试试这个吧
替换它
underScoreWord.push(userGuess);
为了这
underScoreWord[j] = userGuess
你不需要将这封信推到underScoreWord
上。只需用字母替换相应的下划线即可。
for (var j = 0; j < cityPicked.length; j++) {
if (userGuess == cityPicked[j]) {
underScoreWord[j] = userGuess;
}
}