Samuel Paz
Samuel Paz

Reputation: 243

Javascript 2D array strange behavior

I was coding something using javascript arrays but I'm facing a little issue.

I'm running the 'init' function that I've created for 'snake' but the outputs are a little strange for me. I'm sure that's because I'm newbie with javascript. Can anybody explain to me what is happening? And how can I make the code generate the desired output?

var snake = {
    direction : null,
    head : null,
    queue : null,

    init: function(){
        this.direction = RIGHT;
        this.queue = []; // 2D ARRAY
        this.head = []; // 1D ARRAY

        this.insert([1,10]);
        this.insert([2,20]);
        this.insert([3,30]);
    },

    insert: function(x,y){
        this.queue.unshift([x,y]); // INSERTS [X,Y]
        this.head = this.queue[0];

        console.log(this.head + "T0"); // prints: 1,10 T0
        console.log(this.head[0] + " T1 "); // prints: 1,10 T1 
        console.log(this.head[1] + " T2 "); // prints: undefined T2 

        /*
            I was expecting (DESIRED OUTPUT):

            this.head to print 1,1

            this.head[0] to print 1

            this.head[1] to print 10

        */ 

    }

Upvotes: -1

Views: 68

Answers (1)

kalsowerus
kalsowerus

Reputation: 1008

Your function insert takes two arguments; one is used as the first value and one as the second value in the array to unshift to the queue. when calling the function you only pass one argument (the array [1,10]) which well be used as the first element when unshifting, the second element will be undefined.

To solve your problem either call your function using this.insert(1,10); or change the function to only take one argument and then this.queue.unshift(x);.

Upvotes: 2

Related Questions