我正在用 javascript 制作一个刽子手游戏,但我无法理解这个函数中的代码。
这是功能:
function getLetter(word,letter,display){
// This method is called by the Hangman program when your isLetterInWord function
// above returns true.
// The parameters passed in are the guessed letter, the secret word,
// and the current display state of the secret word.
// This method will return a new display state of the secret word based on the matching letter.
// REPLACE THIS CODE WITH YOUR getLetter() METHOD
while (word.search(letter) != -1) {
var index=word.search(letter)
display = display.substr(0, index) + letter + display.substr(index + 1);
word = word.substr(0, index) + '-' + word.substr(index + 1);
}
return display;
}
我不太明白的部分:
display = display.substr(0, index) + letter + display.substr(index + 1);
word = word.substr(0, index) + '-' + word.substr(index + 1);
基本上这个程序需要一个单词,找到字母的数量并用连字符替换它们。例如“船”这个词会变成“----”
上述函数的工作是将字母猜测(正确)替换为相应的连字符。
这是整个项目的背景代码。
// Hangman Project
//RETURN A 'HIDDEN' VERSION OF THE SUPPLIED SECRET WORD
function getDisplay(word)
{
// Given a string, "word", return a hidden version of it consisting
// of dashes for the display.
// REPLACE THIS CODE WITH YOUR getDisplay() METHOD
var disp="";
for (var i=0; i < word.length; i++ ){
disp = disp +'-';
}
return disp;
}
//FIND IF THE LETTER IS IN THE WORD
function isLetterInWord(word,letter){
// Given the word "word", check if it contains the letter "letter".
// REPLACE THIS CODE WITH YOUR isLetterInWord() METHOD
if(word.search(letter) != -1) {
return true;
} else {
return false;
}
}
任何解释这两条车道的帮助将不胜感激。谢谢。