我试图从object2的对象属性中减去object1的objectProperty的值,并且我一直在控制台上获取NaN。以下是示例代码:
object1.objectProperty - object2.object2Property
如果这还不够,我可以发布我项目的完整代码。 如果还有其他方法可以提供帮助,请告诉我。
编辑:这是代码..
var myPokemon = {
health: 25,
defense: 5,
attack: 10,
speed: 5
};
var moves = {
Scratch: 5,
Bite: 5,
Slap: 5,
Growl: 1
};
var computerPokemon = {
health: 20,
defense: 5,
attack: 10,
speed: 7
};
function calcDamage(firstPokemon, secondPokemon, move) {
if(move == moves.Growl){
//starts here
var newDefense = moves.Growl - firstPokemon.defense;
console.log(newDefense);
//ends here
}else{
var newHealth = (firstPokemon.health + firstPokemon.defense) - (secondPokemon.attack + move);
console.log(newHealth);
}
}
编辑:当我做的时候
moves.Growl - firstPokemon.defense || 0;
它返回-4而不是NaN,这是我想要它做的,但回答的人删除了答案,所以这个人已经被那个人回答了。
答案 0 :(得分:1)
使用 parseInt 将值转换为整数,然后进行数学运算。
var value = parseInt(object1.objectProperty,10) - parseInt(object2.object2Property,10);
问题在这里
var newHealth = (Number(firstPokemon.health) + Number(firstPokemon.defense)) - (Number(secondPokemon.attack) + Number(move.Growl));
最后一个Number(move.Growl)
应该是Number(moves.Growl)
moves
而不是move
。在您的情况下,move
只是一个数字而您正在尝试Number(move.Growl)
,这将是NaN,因此您获得了NaN。
答案 1 :(得分:1)
问题是您要在第二个参数中添加对象。你的if语句永远不会执行,我已修复如下
var myPokemon = {
health: 25,
defense: 5,
attack: 10,
speed: 5
};
var moves = {
Scratch: 5,
Bite: 5,
Slap: 5,
Growl: 1
};
var computerPokemon = {
health: 20,
defense: 5,
attack: 10,
speed: 7
};
function calcDamage(firstPokemon, secondPokemon, move) {
if(moves.Growl!=undefined){
//starts here
var newDefense = moves.Growl - firstPokemon.defense;
alert(newDefense);
//ends here
}else{
var newHealth = (Number(firstPokemon.health) + Number(firstPokemon.defense)) - (Number(secondPokemon.attack) + Number(move.Growl));
alert(newHealth);
}
}
calcDamage(myPokemon,computerPokemon,moves)

答案 2 :(得分:1)
通常情况下,如果你得到NaN,你可能正在使用其他元素而不是数字。你确定它们都是数字吗?
只是一个例子:
var x = {}, y = {};
x.r = 10;
y.r = 5;
x.r - y.r; // yields 5