2012-11-06 78 views
0

插入元件的行成多維數組基於索引插入元件的行成多維數組基於索引

例如:

MultiArray = new Array(5); 

MultiArray [0] = new Array(2); 

MultiArray [0][0] = "Tom"; 

MultiArray [0][1] = "scientist"; 


MultiArray [1] = new Array(3); 

MultiArray [1][0] = "Beryl"; 

MultiArray [1][1] = "engineer"; 

MultiArray [1][2] = "Doctor"; 

MultiArray [2] = new Array(2); 

MultiArray [2][0] = "Ann"; 

MultiArray [2][1] = "surgeon"; 

MultiArray [3] = new Array(2); 

MultiArray [3][0] = "Bill"; 

MultiArray [3][1] = "taxman"; 

MultiArray [4] = new Array(2); 

MultiArray [4][0] = "Myrtal"; 

MultiArray [4][1] = "bank robber"; 

MultiArray.splice(1,0, new Array(2){"two","one"}); 

中的最後一行我代碼不起作用。我不確定代碼的其餘部分是否正確。

現在任何人都可以請讓我知道我是否可以在其中某處插入一行元素並將其餘元素向下移動一個索引?

+0

的Java = JavaScript的!我刪除了java標籤。 –

+1

@Sushil爲什麼?完全可以寫'新數組(10)' –

+0

@Sushil:不,它不是:)。繼續嘗試: 'var a = new Array(10); console.log(a.join(「wat」));' –

回答

2

嘗試:

MultiArray.splice(1,0, ["two","one"]); 
4

你不小心寫new Array{}這是錯誤的 - 你的命令應該是:

MultiArray.splice(1,0, new Array(2)("two","one")); // no curled brackets!! 

甚至更​​好

MultiArray.splice(1,0, ["two","one"]); 

總之,在JavaScript中new Array()應避免符號(js自動控制維數它是數組,不需要預先分配或聲明它)。相反,你可以這樣寫:

MultiArray = []; 

所以,你可以直接寫:

MultiArray = [[ "Tom","scientist"],["Beryl","engineer","Doctor"], 
       ["Ann","surgeon"],["Bill","taxman"],["Myrtal","bank robber"]]; 

MultiArray.splice(1,0, ["two","one"]);