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.

3
  • I dont fully understand what you want, but your attackUp function does var i = 0; Commented Jul 10, 2017 at 0:28
  • I want to increase the xpforlevel[i] by 1 every time I hit over the xp I need to level. Commented Jul 10, 2017 at 0: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. Commented Jul 10, 2017 at 0:40

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.