Coders Stike Back - javaScript Array

I am unable to store values in an array. I’m pretty sure my code is sound.

    var cpX = nextCheckpointX,
        cpY = nextCheckpointY,
        mapX = [],
        mapY = [];

    if(mapX.indexOf(cpX) === -1){
        mapX.push(cpX);
        mapY.push(cpY);
        printErr("should be pushing");
    }

"should be pushing" prints to the console, but if I print mapX.length the console only ever prints 1. I have a printErr() in my else statement that never prints.

I don’t understand. You push only one value in mapX, how the length could be anything else than 1 ?

When cpX changes, the if statement checks to see if it is the array or not, if not it pushes it to the array.

Its as if the array keeps emptying after a checkpoint is crossed

=== compares types, not values
var1 === var2
is the same as
typeof(var1) == typeof(var2)

=== does not perform any type conversion before comparing, where == does.

2 === 2 //true
2 === '2' //false

3 == 3 //true
3 == '3' //true

array.indexOf(value) returns the index at which the value is stored, which is a number, so the explicit === should work as no type conversion is required.

however, I have tried == and there is no change to my problem.

1 Like

Is your var statement outside the while loop? If it is inside the loop, then your vars will get re initialized every game turn.

3 Likes

Perfect!! thanks mixolyde! my arrays were inside the loop

1 Like