我为这项任务付出了太多努力。我需要做到;检查我写的单词是否与数组中的单词匹配。 (单个字母)。如果是,它应该用该单词中的字符替换下划线!我该怎么办?
这是一个像hangman btw这样的游戏 这是我的代码:
<script>
var words = ["kite", "boom", "zoom", "tall", "table", "biscuit", "pie"];
window.addEventListener("load", function() {
var submitbtn = document.getElementById("button")
var userInput = document.getElementById("userInput");
submitbtn.addEventListener("click", checkAnswer, false);
var wordElt = document.getElementById("word");
var word = words[Math.floor(Math.random() * words.length)];
for ( var i=0; i < word.length; i++ ) {
//display += "_ ";
wordElt.textContent += " _ ";
}
var split = word.split("");
console.log(word)
});
function check(){
}
答案 0 :(得分:0)
你不能用字符串替换字母,因为javascript字符串是不可变的 - 请参阅this answer,你可以从中借用
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
然后(如果您编写Hangman游戏的代码),您可以使用字符串indexOf方法替换出现的事件:
var theWord = "H___o";
var theLetter = "l";
var keyWord = "Hello";
while(true) {
var i = keyWord.indexOf(theLetter);
if(i==-1) break;
theWord = theWord.replaceAt(i,theLetter);
keyWord = keyWord.replaceAt(i,"_");
}
// theWord = H_llo
// keyWord = He__o