我实际上一无所知,我用node启动这个javascript代码,然后我希望它只显示数字100和69,但这是它第一次启动时的输出:
未定义未定义100 69 100 69
。第一次变量显示为未定义..我做错了什么?
此外,此代码仅用于测试目的..
startCrash();
var currentCrashNumber = 100;
var currentCrashSpeed = 100;
function startCrash(){
sendCrashNumber();
setInterval(function(){
if(currentCrashSpeed > 0){
currentCrashSpeed = currentCrashSpeed+-1;
}else{
clearInterval(this);
}
}, 1000);
}
var lijntjespeed = 69;
function sendCrashNumber() {
console.log(currentCrashNumber);
console.log(lijntjespeed);
io.sockets.emit('message', {
crashMultiplier: currentCrashNumber,
type: 'updateCrash'
});
setTimeout(sendCrashNumber, currentCrashSpeed);
}
最佳答案
您的问题与 variable hoisting
有关,因为您在代码顶部调用了 startCrash
,并且此时变量 currentCrashNumber
和 currentCrashSpeed
尚未初始化。发生这种情况是因为这些变量的声明被提升到代码的顶部,因此当调用函数时,它们首先是未定义的。
这是提升后代码的行为:
var currentCrashNumber; // undefined
var currentCrashSpeed; // undefined
var lijntjespeed; // undefined
startCrash();
currentCrashNumber = 100;
currentCrashSpeed = 100;
lijntjespeed = 69;
function startCrash(){
sendCrashNumber();
setInterval(function(){
if(currentCrashSpeed > 0){
currentCrashSpeed = currentCrashSpeed+-1;
}else{
clearInterval(this);
}
}, 1000);
}
...
只需向下移动对 startCrash
的调用,它就会按预期工作。
代码中的另一个问题,由 jfriend00 指出,位于 startCrash
函数的 clearInterval
调用中。在您的代码中,this
作为参数传递,但它需要是一个时间处理程序。
要解决此问题,您可以将 setInterval
(这是一个计时器)的返回值分配给一个变量并使用它:
function startCrash(){
sendCrashNumber();
var timer = setInterval(function(){
if(currentCrashSpeed > 0){
currentCrashSpeed = currentCrashSpeed+-1;
}else{
clearInterval(timer);
}
}, 1000);
}
关于javascript - 变量显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44863347/