首先,要知道如何建立二維數組。javascript
http://blog.csdn.net/wangyuchun_799/article/details/38460515html
這裏引入一種最簡單的。java
<script type="text/javascript"> var arr = new Array(); //建立一個一維數組 for (var i = 0; i < 2; i++) { arr[i] = new Array(); for (var j = 0; j < 3; j++) { //將每個子元素有定義爲數組 arr[i][j] = ""; //此時的array1[i][j]能夠視爲二維數組,並初始化二位數組爲空字符串 } } arr[0][0]=1; //給arr賦值 arr[0][1]=2; arr[0][2]=3; arr[1][0]=11; arr[1][1]=22; arr[1][2]=33; document.write(arr); //1,2,3,11,22,33 </script>
二維數組主要用來幹什麼呢?博主如今要用到的是將HTML中表格的值添加到二維數組中,以便後續對錶格進行單元格合併啊之類的操做(用二維數組進行此類操做更利於後續的代碼維護)數組
好的,那麼接下來讓咱們看看怎麼用JavaScript實現將表格裏的元素添加到二維數組中吧~ui
<script> var tr = document.getElementsByTagName('tr'); //獲取HTML中表格的tr var td = document.getElementsByTagName('td'); //獲取HTML中表格的td var arr2 = new Array() //定義二維數組arr2 for (var i = 0; i < tr.length-1; i++) { //由於忽略了表頭th,因此少了一組tr,故i<tr.length-1 arr2[i] = new Array(); for (var j = 0; j < td.length/(tr.length-1); j++) { //每一組tr中有的td個數:td.length/(tr.length-1) arr2[i][j] = ""; //初始化二位數組爲空字符串 } } for (var x = 0; x < tr.length-1; x++) { for (var y = 0; y < td.length/(tr.length-1); y++) { arr2[x][y] = td[x*(td.length/(tr.length-1))+y].innerText; //td[?].innerText獲取第?個td中的值,?= x*(td.length/(tr.length-1))+y } } </script>
現附上HTML部分代碼spa
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>二維數組的創建</title> </head> <body> <h3>用JS將表格數據寫入二維數組</h3> <div class="table"> <table id="tb" width="400px" border="1" cellspacing="3" cellpadding="3"> <caption style="margin-bottom: 15px">table</caption> <tr> <th>year</th> <th>city</th> <th>name</th> <th>age</th> <th>score</th> <th>expense</th> </tr> <tr> <td>2015</td> <td>北京</td> <td>花花</td> <td>18</td> <td>600</td> <td>12222</td> </tr> <tr> <td>2015</td> <td>北京</td> <td>明明</td> <td>19</td> <td>620</td> <td>15000</td> </tr> <tr> <td>2015</td> <td>上海</td> <td>麗麗</td> <td>16</td> <td>630</td> <td>11000</td> </tr> <tr> <td>2016</td> <td>北京</td> <td>凱凱</td> <td>20</td> <td>660</td> <td>13000</td> </tr> <tr> <td>2016</td> <td>重慶</td> <td>琪琪</td> <td>19</td> <td>655</td> <td>10000</td> </tr> <tr> <td>2016</td> <td>成都</td> <td>菲菲</td> <td>20</td> <td>570</td> <td>19000</td> </tr> <tr> <td>2016</td> <td>成都</td> <td>妮妮</td> <td>17</td> <td>609</td> <td>16000</td> </tr> <tr> <td>2016</td> <td>河南</td> <td>娃娃</td> <td>18</td> <td>580</td> <td>13000</td> </tr> <tr> <td>2016</td> <td>上海</td> <td>tiantian</td> <td>18</td> <td>590</td> <td>16000</td> </tr> </table> </div> </body> </html>
效果如圖所示.net
好比我調用alert(arr[0][0])便可獲得2015.code
此時,表格已經傳到二維數組中了。htm