2017-02-22 104 views
0

我創建了一個函數生成一個表:2維陣列未定義

function TabGen(sRow){ 
var sResultat = "<table border = 1 px solid black>"; 

for(var iCompt = 0; iCompt<arguments.length; iCompteur++) 
{ 
    sResultat += ("<td>" + arguments[iCompteur]+ "</td>") 
} 
sResultat += "</table>"; 
return sResultat; 
} 

然後創建其使用2 dimensionnal陣列打印出在屏幕上的表3行4列的功能。這:

function AfficheTab() { 

var aTab = [[0,0,0,1],[0,0,0,2],[0,0,0,3]]; 

for(var iCompt=0; iCompt < aTab.length; iCompt++) 
{ 
    return(aTab); 
} 
} 

爲什麼我會得到一個undefined?如果不對,我該如何解決這個問題?

打印功能:

(function(){ 

      var aLesDiv = document.querySelectorAll("#global div"); 

      aLesDiv[0].innerHTML = TabGen((AfficheTab(aTab))); 


     })(); 
+0

哪裏是你? – Kornflexx

+0

您正在定義一個名爲AfficheTab的函數,它不接收任何參數,並且傳遞'aTab'作爲參數。這將無法工作。 –

+1

'「

」'不會是有效的HTML代碼... – Mistalis

回答

0

arguments本身是一個數組。如果要使用數組,請使用參數[index] [arrayIterator] 在使用二維數組時,必須使用2個數組。

function TabGen(sRow){ 
    var sResultat = "<table border = 1 px solid black>"; 

    for(var iCompt = 0; iCompt<arguments[0].length; iCompteur++){ 
    sResultat += ("<td>" + arguments[0][iCompteur]+ "</td>") 
    } 
    sResultat += "</table>"; 
    return sResultat; 
    } 
0

看到你的函數,它返回什麼?一排還是矩陣?矩陣...

function AfficheTab() { 

    var aTab = [[0,0,0,1],[0,0,0,2],[0,0,0,3]]; 

    for(var iCompt=0; iCompt < aTab.length; iCompt++)//useless loop 
    { 
     return(aTab); //the code stops in the first loop and return [[0,0,0,1],[0,0,0,2],[0,0,0,3]] 
    } 
} 

所以你TabGen可以通過做處理所有:

function TabGen(aTab) { 
    aTab.forEach((row) => { 
     row.forEach((cell) => { 
     //Do something with your row values (cell) 
     }); 
    }); 
    return false;//return your return stuff 
} 

我想你想有一個表,所以......

function TabGen(aTab) { 
    var html = []; 

    html.push('<table border="1">'); 

    aTab.forEach((row) => { 
     html.push('<tr>'); 

     row.forEach((cell) => { 

     html.push('<td>',cell,'</td>'); 

     }); 

     html.push('</tr>'); 
    }); 

    html.push('</table>'); 

    return html.join(''); 
}