-1

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

        */ 

    }

1 Answer 1

2

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);.

Sign up to request clarification or add additional context in comments.

1 Comment

Ohhh, I see. I was calling the function wrongly. Thank you for your help.

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.