The subtraction assignment operator [-=
] subtracts the value of the right operand from a variable and assigns the result to the variable. Try it
Syntax
Examples
Using subtraction assignment
// Assuming the following variable
// bar = 5
bar -= 2 // 3
bar -= 'foo' // NaN
Specifications
ECMAScript Language Specification # sec-assignment-operators |
Browser compatibility
BCD tables only load in the browser
See also
I'm working on a simple game and I've gotten as far as coding it so that when you click on an attack button it should generate a random number based on a base and strength then subtract that from the enemy's health but the subtracting part doesn't seem to work. It always outputs NaN
.
var playerHealth=100;
var enemyHealth=100;
var strength=10;
function begin[]{
document.getElementById['playerhealth'].innerHTML = playerHealth;
document.getElementById['enemyhealth'].innerHTML = enemyHealth;
}
function hitEnemy[]{
var attack=Math.floor[Math.random[]*20 + strength];
var enemyHealth = enemyHealth - attack;
document.getElementById['damage'].innerHTML = attack;
document.getElementById['enemyhealth'].innerHTML = enemyHealth;
}
playerhealth
enemyhealth
You Did:damage
It may have something to do with not specifically making sure that they're integers but I'm not sure how to do that.
Igor
32.3k14 gold badges76 silver badges111 bronze badges
asked Nov 3, 2011 at 0:34
because you redefine the enemyHealth var inside hitEnemy function. Remove the var to fix it.
function hitEnemy[]{
var attack=Math.floor[Math.random[]*20 + strength];
enemyHealth = enemyHealth - attack;
document.getElementById['damage'].innerHTML = attack;
document.getElementById['enemyhealth'].innerHTML = enemyHealth;
}
answered Nov 3, 2011 at 0:40
heisthedonheisthedon
3,6023 gold badges20 silver badges24 bronze badges
Here is the most immediate problem. You need to remove
var
from the enemyHealth
decalaration inside of hitEnemy
. This creates a new variable named enemyHealth
intsead of modifying the first one.
enemyHealth = enemyHealth - parseFloat[attack];
Additionally you should be calling begin
at the end of every hitEnemy
call in order to update the scores. Here's a working version of the code
- //jsfiddle.net/YbCay/
answered Nov 3, 2011 at 0:37
JaredParJaredPar
712k146 gold badges1216 silver badges1441 bronze badges
1
To add to Jared's response...
var enemyHealth = enemyHealth - attack;
is shorthand for...
var enemyHealth;
enemyHealth = enemyHealth - attack;
First, enemyHealth
is defined as undefined
* within the scope of hitEnemy
. Now, two variables named enemyHealth
exist, but the inner one "shadows" the outer one, making it impossible to refer to the outer one. So, attack
is subtracted from undefined
, producing NaN
.
* which sounds nonsensical, I know
answered Nov 3, 2011 at 2:03
davidchambersdavidchambers
23k16 gold badges74 silver badges101 bronze badges