2013-03-13 205 views
0

我創建了一個數組:二維數組 - 將對象添加到域

var test = new Array(5); 
for (i=0; i<=5; i++) 
{ 
test[i]=new Array(10); 
} 

,現在我想添加對象字段:

test[0][5].push(object); 

但出現錯誤:

Uncaught TypeError: Cannot call method 'push' of undefined

我使用「推」,因爲我想把這個字段放入0-4個對象,但我不知道到底會有多少對象。 我應該如何改變它以使其正確?

+3

你得到錯誤的原因是'試驗[0] [5]'是'返回undefined'(自陣列中沒有任何東西在測試[0]),並調用'push'。我不確定我是否明白你的意思,「我想把這個字段放到這個字段中,但是我不知道到底會有多少個對象。」 – Default 2013-03-13 20:12:09

+0

在一個字段中可以從0到4個對象 – Piotrek 2013-03-13 20:42:43

回答

1

將「< =」更改爲「<」。

for (i = 0; i < 5; i++) 

數組是從零開始的,所以如果你有5個插槽數組,你要訪問的最後一個插槽可以使用:

anArray[4] 
+0

是的,但這不是OP正面臨的錯誤 – Bergi 2013-03-13 20:17:20

+0

是的你是對的。當我第一次看這些東西時,錯誤太多了。 – zachzurn 2013-03-13 20:20:25

0

使用前推問值是一個數組

if(test[0][5] instanceof Array) 
    test[0][5].push(object); 
0
test[0][5] = new Array(); // you need initialize this position in Array 
test[0][5].push(object); // and then push object 

test[0][5] = [object]; // directly create a new Array with object 

,但如果你只是想在這個位置的對象,你應該這樣做:

test[0][5] = object; 
4

表達test[0]指的是一個新的Array實例,經行創建:

test[i]=new Array(10); 

但是,中沒有這個數組。因此,test[0][5]引用一個未定義的對象。您需要將初始化爲,然後才能對其執行push()操作。例如:

test[0][5] = []; // Set [0][5] to new empty array 
test[0][5].push(object); // Push object onto that array 

甚至:

test[0][5] = [object]; // Set [0][5] to one item array with object 
+0

但這個對象將在應用程序運行時添加。我無法清除這個數組。 – Piotrek 2013-03-13 20:39:46

+0

然後,在將'test [i]'設置爲新數組後,循環訪問該數組,並將每個索引設置爲一個空數組。 – 2013-03-13 20:55:52

2
var test = new Array(5); 
for (i=0; i<=5; i++) 
{ 
    test[i]=new Array(); 
} 

這會讓你創建一個多維數組。變量測試中的每個元素都是一個數組。

從這裏你可以做

test[0].push("push string"); 
test[0].push("push string2"); 

從這裏

test[0][1] will contain "push string2"