类型错误:Math.floor()不是一个函数。

7

我有一个基于Node.js的Discord Bot,使用discord.js编写,我想要制作一个回合制战斗系统,因此我编写了一个伤害计算函数。

var damage = parseFloat( Math.floor( Math.random() * skill.dmg/5 ) + skill.dmg )
//some other factors, none causing the error
damage = Math.floor( damage )

代码非常简单,但出现错误:

类型错误:Math.floor(...)不是函数

我已经检查过每篇帖子,按照他们所做的做了,但没有任何作用,我已经清除了缓存,我已经检查了camelCase,...

我该怎么办?

主要功能代码:

var damage = parseFloat( Math.floor( Math.random() * skill.dmg/5 ) + skill.dmg )
damage += weapons[ user.inv.armor.weapon ].damage
var crit = ( ( Math.floor( Math.random() * 100 ) + skill.crit ) > 100 ? ( Math.random() + 1 ).toFixed( 1 ) : 1 )
damage *= crit
if ( !tags.includes( 'ignorant' ) ) {
    damage -= enemy.stats.res
    damage *= parseFloat( "0." + ( 100 - enemy.res[ tags[1] ] ) )
    damage -= shields[ enemy.inv.armor.shield ].res
}
damage = Math.floor( damage )damage = Math.floor( damage )
( monster ? enemy.hp -= damage : enemy.profile.hp -= damage )

7
尝试检查 Math,它可能在某个时候被重新定义过了。 - Carcigenicate
这可能会有所帮助:https://www.codecademy.com/en/forum_questions/5275475bf10c601cb4002593 - Praveen Kumar Purushothaman
2
你确定错误发生在那里吗?该错误消息告诉你Math.floor()返回值不是一个函数。在damage = Math.floor(damage)之后的下一行是什么?那一行缺少分号,所以下一行可能是问题的原因。 - Pointy
1
我建议你真的应该习惯使用分号,无论哪种方式。 - Pointy
1
你真的不应该在一个数字上调用 parseFloat - Bergi
显示剩余6条评论
1个回答

16

Math.floor确实存在,这不是与Math有关的问题。如果Math.floor不是函数,则错误将为:

TypeError:Math.floor不是函数

但你得到的是

TypeError: Math.floor(...) is not a function

这意味着你正在做:

Math.floor(damage)();

请在damage = Math.floor(damage)之后贴上代码,该代码很可能是(...),这样我们就可以确定具体的错误位置。

try {
  Math.floors(5); // Added extra S on purpose
} catch(e){
  console.log(e.message);
}


try {
  Math.floor(5)();
} catch(e){
  console.log(e.message);
}

更新

以下代码触发了错误:

damage = Math.floor( damage ) 
( monster ? enemy.hp -= damage : enemy.profile.hp -= damage )

你所做的是调用Math.floor的结果,它返回一个数字。

damage = Math.floor( damage ); // ; this bad boy was all that was missing.
monster ? enemy.hp -= damage : enemy.profile.hp -= damage;

这就是为什么分号很重要的原因!

在JavaScript中,您是否建议在每个语句后使用分号?

是的,我绝对建议


我之前是这样写的: damage = Math.floor( damage ) ( monster ? enemy.hp -= damage : enemy.profile.hp -= damage ) 但在@Pointy的评论后,我意识到... - Lilly
我会将此添加到我的答案中,这样将来有人可以从中受益。不要忘记添加完整的代码或最小化、完整和可验证的示例,以便我们能够帮助您!https://stackoverflow.com/help/mcve - Marcos Casagrande
我已经添加了出错的部分,这样人们就可以看到错误在哪里了。 - Lilly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接