You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:57:32