0
我編寫的東西使用JavaScript數組,但我面臨一個小問題。Javascript二維數組奇怪的行爲
我正在運行爲'蛇'創建的'init'函數,但輸出對我來說有點奇怪。我敢肯定,這是因爲我是javascript新手。有人可以向我解釋發生了什麼嗎?我怎樣才能讓代碼生成所需的輸出?
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
*/
}
哦,我明白了。我錯誤地調用了函數。感謝您的幫助。 –