2012-05-11 46 views
0

正在處理需要爲數組添加點的項目。以下是創建,然後試圖將一個對象添加到陣列的代碼:JavaScript 2D數組未捕獲TypeError

var points = []; 
    points[0] = []; 
    points[0][0] = 0; //x-coord 
    points[0][1] = 0; //y-coord 

points[points.length][0] = x; //Breaks on this line 
points[points.length][1] = y; 

確切的錯誤我得到的是遺漏的類型錯誤:無法設置的不確定財產「0」。每次按下按鈕時都會運行此代碼,其他值已經設置爲ints。我認爲JavaScript允許你在數組中設置值?

+0

我推薦使用對象的數組,而不是:'分= [];點[0] = {x:0,y:0};' – jimw

回答

2

最後一個數組索引是points.length - 1。現在,您正在處理數組末尾的元素(即undefined),並嘗試將其「0」屬性的值設置爲x。在undefined上設置屬性是不允許的。

+0

謝謝,只要我發佈,我意識到我正在初始化第二個數組,並必須編寫一個函數來實例化內部數組。儘管感謝您的及時答覆! – wchristiansen

1

您的數組中包含:

var points = [ 
    [0,0] 
] 

然而

points[points.length] 
//is 
points[1] 

不存在。你必須首先創建數組,在你實際添加的東西給它

Here's a sample

var length = points.length; //cache value, since length is "live" 
points[length] = [];   //using the cached length, create new array 
points[length][0] = x;  //add values 
points[length][1] = y;