为什么第8行的警报返回“未定义”?如果我在第5行提醒相同的事物,它将从单词数组中返回一个随机单词。

var words = ["elephant", "puppy", "cat", "table", "staircase"]
var chosenWord = words[Math.floor(Math.random()*words.length)]
var typedWord = ""
$(document).ready(function(){
$('.word-box').html(chosenWord)
    $(document).keypress(function(e) {
        typedWord += letters[e.which]
        alert(chosenWord)
        if (typedWord === chosenWord) {
            var chosenWord = words[Math.floor(Math.random()*words.length)]
            $('.word-box').html(chosenWord)
            typedWord = ""
        };
    });
});

最佳答案

猜测。问题是在keypress事件处理程序内的下面这行:

var chosenWord = words[Math.floor(Math.random()*words.length)]


当由于变量提升而用var声明变量时,最好在函数开始时声明它。所以我们的代码实际上是:

var words = ["elephant", "puppy", "cat", "table", "staircase"]
var chosenWord = words[Math.floor(Math.random()*words.length)]
var typedWord = ""
$(document).ready(function(){
$('.word-box').html(chosenWord)
    $(document).keypress(function(e) {
        //UPDATE
        var chosenWord;
        typedWord += letters[e.which]
        alert(chosenWord)
        if (typedWord === chosenWord) {
            //UPDATE
            chosenWord = words[Math.floor(Math.random()*words.length)]
            $('.word-box').html(chosenWord)
            typedWord = ""
        };
    });
});


解:

尝试在var事件处理程序内的chosenWord之前删除keypress

看看var hoisting

关于javascript - 为什么变量在$(document).keypress中变得未定义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23852624/

10-09 21:43