JavaScript中Float值使用后变为NaN的问题求助
问题根源:空队列导致的
undefined赋值 你的问题核心出在Animate函数处理transformQue的逻辑上。当队列里没有待处理的旋转值时,this.transformQue.pop()会返回undefined,而你直接把这个值加到this.orientation上,导致它变成NaN(数字与undefined相加的结果就是NaN)。
具体代码分析
看你Animate函数里的这段关键代码:
var rotation = this.transformQue.pop(); // ... renderContext.rotate( this.orientation += rotation );
- 直接调用
mySprite.QueRotation(.1)时,每次调用都会往队列里塞一个有效数值,Animate执行时pop()总能拿到值,所以orientation能正常累加,程序运行正常。 - 但调用
MySpriteClockWise四次后,队列里的四个Math.PI/2会被pop()取完,后续执行Animate时队列是空的,pop()返回undefined,this.orientation += undefined就会让orientation变成NaN。 - 哪怕你不调用
QueRotation,第一次执行Animate时队列本来就是空的,同样会触发这个问题。
修复方案
只需要在取旋转值时,处理队列空的情况,给rotation一个默认值0即可,有两种直观的写法:
写法1:使用逻辑或运算符
修改Animate里的旋转值获取逻辑:
var rotation = this.transformQue.pop() || 0;
如果pop()返回undefined(队列空),||会取后面的0,这样this.orientation += 0不会改变它的值,避免变成NaN。
写法2:显式检查队列长度
如果你觉得逻辑或不够直观,也可以显式判断队列是否为空:
var rotation = 0; if (this.transformQue.length > 0) { rotation = this.transformQue.pop(); }
额外验证(可选)
你可以在Animate函数里加个控制台输出,直观确认问题:
var rotation = this.transformQue.pop(); console.log('当前旋转值:', rotation); // 队列空时,这里会输出undefined
修复后,这个值在队列空时会变成0,orientation就能一直保持正常数值了。
内容的提问来源于stack exchange,提问作者The Floating Brain
相关产品推荐
相关产品推荐

