我试图使用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];
}
}
我会首先将其添加到函数的顶部和底部:
console.log('starting', questionID);
console.log('ending', questionID);
然后使用您的调试日志查看发生了什么...或者,您可以添加手表并使用Firebug或Chrome逐步完成代码
还想知道为什么你不使用jQuery...
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