0

I trying to make a small text based rpg game, but I came across array in js and then I came to problems, I failing to increase the index number by using i instead of 0 like myArray[i]

I made a jsfiddle so you guys can see what I mean.

jsfiddle

When you press the button til you get a warming, it should increase the i to 2, but it don't, but still comes with warming and increasing the attack variable.

Suit Games
  • 11
  • 9
  • I dont fully understand what you want, but your `attackUp` function does `var i = 0;` – ASDFGerte Jul 10 '17 at 00:28
  • I want to increase the xpforlevel[i] by 1 every time I hit over the xp I need to level. – Suit Games Jul 10 '17 at 00:29
  • Welcome to Stackoverflow. Your code really should be posted *here*. There are facilities that allow you to make "snippets" of code that often are sufficiently functional that you don't need an offsite service like jsfiddle at all, though a jsfiddle link is OK. But the code should be at least posted as static code in the question itself here. – Pointy Jul 10 '17 at 00:40

2 Answers2

1

This is your attackUp function:

function attackUp(){
    var i = 0;
    var attackCost = xpforlevel[i];
    if (attackCost < attackxp) {
        alert("WARMING!");
        attack++;                           
          document.getElementById('attack').innerHTML = attack;
        i++;
        document.getElementById('i').innerHTML = i;
    }
}

Notice that your var i = 0 statement doesn't really make sense (because everytime attackUp is called, i will be reset to = 0 at the beginning). To fix that, erase this var i = 0 statement from your function and put in the beginning of your JS code:

var i = 0;
var attackxp = 0;
var attack = 1;

Further, your function will only update i if attackCost < attackxp, otherwise it will change nothing. You need to put the i++; statement outside your if-block, like this:

function attackUp(){
    //erase this line: var i = 0;
    var attackCost = xpforlevel[i];
    i++; //added this line
    if (attackCost < attackxp) {
        alert("WARMING!");
        attack++;                           
          document.getElementById('attack').innerHTML = attack;
        //erase this line: i++;
        document.getElementById('i').innerHTML = i;
    }
}
flen
  • 1,905
  • 1
  • 21
  • 44
0

As your i is a local variable, it is initiated as 0 every time you call attackUp(). You should put it besides attackxp and attack.

For more information about the scope of variable in JavaScript, see w3schools or this question.