JavaScript跟踪全局变量?

时间:2013-11-07 11:13:25

标签: javascript regex global-variables

我试图使用questionID变量来跟踪一些问题和答案。 但是,每次运行我的函数时,似乎我都有变量丢失内存的问题?这就是我的想法。

当我要求:颜色,然后跟进答案:粉红色,紫色或绿色,它跳到最后一个声明; else if(questionID == -1)这不是我的意图。

如何解决此问题? 我在本地运行脚本。

var questionID = -1;

function askQ() {
    var findme = document.getElementById('askBox').value.toLowerCase();
    var dontUnderstand = new Array();
    dontUnderstand[0] = "Excuse me, What did You say ?";
    dontUnderstand[1] = "Sorry, I cant understand You now. ^_^";
    dontUnderstand[2] = "Sorry!, I got to go now... CU !";
    dontUnderstand[3] = "ohh... Can you repeat that one more time ?";
    var randomIndex = Math.round(Math.random() * 3);
    if (findme.match(/(age|old)/)) {
        document.getElementById('bubble').innerHTML = "ohh,, I am " +
            obj1.age + " years old, How old are You ?";
    }
    if (!isNaN(findme)) {
        document.getElementById('bubble').innerHTML = "ohh.. that's kinda old !";
    }
    if (findme.match(/(color)/)) {
        document.getElementById('bubble').innerHTML = "My favourite color " +
            " is Purple, What's yours ?";
        questionID = 6;
    }
    if (findme.match(/(pink|purple|green)/) && questionID == 6) {
        document.getElementById('bubble').innerHTML = "well...that's cute !!";
        questionID = -1;
    }
    if (findme.match(/(hi|hello)/)) {
        document.getElementById('bubble').innerHTML = "Hi there, nice to meet You !";
    } else if (questionID == -1) {
        document.getElementById('bubble').innerHTML = dontUnderstand[randomIndex];
    }
}

2 个答案:

答案 0 :(得分:1)

我首先将addint添加到函数的顶部和底部:

console.log('starting', questionID);


console.log('ending', questionID);

然后使用您的调试日志查看正在发生的事情......或者您可以使用firebug或chrome添加监视并逐步执行代码

还想知道你为什么不使用jQuery ......

答案 1 :(得分:0)

 if(findme.match(/(pink|purple|green)/) && questionID == 6){
              document.getElementById('bubble').innerHTML = "well...that's cute !!";
      // You're setting it to -1.
      questionID = -1;
  }

此外,为什么不通过questionID askQ函数的属性来限制对全局对象的污染。

askQ.questionID = 6