我正在使用javascript进行刽子手游戏。这是一堂课。我是javascript和DOM的菜鸟,所以请善待。此时,我只想在控制台日志中打印出SOMETHING。我已经花了几天时间去除了我所有的功能和游戏过程,除了这里展示的少数只是试图让一些东西起作用。我的思维过程是在循环内不会改变而且不需要在html中动态更新的变量不需要是刽子手游戏的属性。但是,当我运行以下代码只是为了得到一些工作到console.log,我得到userGuess没有定义。我以为我是通过为它指定keyUp事件的值来定义它的。如果我将userGuess作为hangman游戏的属性,然后使用hangmanGame.userGuess更新我的所有其余代码,我会收到所有这些意外的令牌错误。
有什么想法吗?
//Variables===============================================================
var hangmanGame = {presidents: [
"WASHINGTON",
"ADAMS",
"JEFFERSON",
"MADISON",
"MONROE",
"JACKSON",
"VANBUREN",
"HARRISON",
"TYLER",
"POLK",
"TAYLOR",
"FILLMORE",
"PIERCE",
"BUCHANAN",
"LINCOLN",
"JOHNSON",
"GRANT",
"HAYES",
"GARFIELD",
"ARTHUR",
"CLEVELAND",
"HARRISON",
"MCKINLEY",
"ROOSEVELT",
"TAFT",
"WILSON",
"HARDING",
"COOLIDGE",
"HOOVER",
"TRUMAN",
"EISENHOWER",
"KENNEDY",
"NIXON",
"FORD",
"CARTER",
"REAGAN",
"BUSH",
"CLINTON",
"OBAMA"
],
wrongAllowed: 7,
goodLetters: 0,
wordArray: [],
badArray: [],
wins: 0,
//functions=========================================================
startGame: function() {
var word = hangmanGame.presidents[Math.floor(Math.random() * hangmanGame.presidents.length)];
},
}
function write() {
console.log("President" + word);
}
//main process===============================
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toUpperCase();
}
if (userGuess == 'A'){
write();
}
答案 0 :(得分:3)
将其更改为此
// Main process
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toUpperCase();
if (userGuess === 'A') {
write();
}
}
答案 1 :(得分:0)
在if
事件处理程序中包含keyup
语句;来自return
函数的word
handman.startGame
变量,将word
传递给write
函数
//Variables===============================================================
var hangmanGame = {
presidents: [
"WASHINGTON",
"ADAMS",
"JEFFERSON",
"MADISON",
"MONROE",
"JACKSON",
"VANBUREN",
"HARRISON",
"TYLER",
"POLK",
"TAYLOR",
"FILLMORE",
"PIERCE",
"BUCHANAN",
"LINCOLN",
"JOHNSON",
"GRANT",
"HAYES",
"GARFIELD",
"ARTHUR",
"CLEVELAND",
"HARRISON",
"MCKINLEY",
"ROOSEVELT",
"TAFT",
"WILSON",
"HARDING",
"COOLIDGE",
"HOOVER",
"TRUMAN",
"EISENHOWER",
"KENNEDY",
"NIXON",
"FORD",
"CARTER",
"REAGAN",
"BUSH",
"CLINTON",
"OBAMA"
],
wrongAllowed: 7,
goodLetters: 0,
wordArray: [],
badArray: [],
wins: 0,
//functions=========================================================
startGame: function() {
var word = hangmanGame.presidents[Math.floor(Math.random() * hangmanGame.presidents.length)];
return word
}
}
function write(word) {
console.log("President " + word);
}
//main process===============================
var hangman = hangmanGame.startGame();
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toUpperCase();
if (userGuess == 'A') {
write(hangman);
}
}