为什么变量在$(document).keypress中未定义?

时间:2014-05-25 06:24:35

标签: javascript jquery keypress

为什么第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 = ""
        };
    });
});

2 个答案:

答案 0 :(得分:4)

猜测。问题出在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

答案 1 :(得分:0)

问题是你的按键事件中的var字,正如Niranjan所说。而且,我不知道这对你来说是否更好。如果是,试试吧。这样就消除了选择重复单词的可能性。

var words = ["elephant", "puppy", "cat", "table", "staircase"];
words.sort(function() { return 0.5 - Math.random() };
var currentWord = 0;
var chosenWord = words[0];
var typedWord = "";
$(document).ready(function(){
    $('.word-box').html(chosenWord);
    $(document).keypress(function(e) {
        typedWord += letters[e.which];
        if (typedWord === chosenWord && currentWord < words.length - 1) {
            currentWord++;
            chosenWord = words[currentWord];
            $('.word-box').html(chosenWord);
            typedWord = "";
        };
    });
});