浮云間
2022-10-27 15:24:05
<html><head><meta charset="utf-8"/></head><form name="formular"><label>Zeilen eingeben: <input id="inpZeile" name="inpZeile" type=number value="2"></label><label>Spalten eingeben: <input id="inpSpalte" name="inpSpalte" type=number value="2"></label></form><button type="button" onclick="machTabelle(document.forms.formular.elements.inpSpalte.value, document.forms.formular.elements.inpZeile.value)" id="MachTabelle">Tabelle erstellen</button></html><script src="testen.js"></script>var table ='';function machTabelle(x,y){ var myArr = new Array(x); for (var i = 0; i < myArr.length; i++) { myArr[i] = new Array(y); }; console.log (myArr); for(var i=0; i<x; i++) { table += '<tr>'; for(var j =0;j<y;j++) { table += '<td>' +j+ '</td>'; } table += '<tr>'; } document.write('<table border=1>' +table+ '</table>');}我改變了一些東西,但它總是返回一個 1D 數組而不是 2D ,只使用相同的數組代碼作為片段工作。目標是制作數組和表格,獲取用戶輸入的大小,當然稍后制作一個包含數組內容的表格。
1 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
該表在您首先循環輸入x然后循環輸入時工作y
請注意,函數中沒有變量table。var table = "";例如,您可以添加myArr不用于生成表的示例。
當您創建一個數組Array(y)時y,輸入是一個字符串。(注意函數參數和輸入字段的順序。)
請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array
例如machTabelle('3', '2')查看內聯注釋:
// Array with index 0 has the value of the input "2" as you are passing a string
var myArr = new Array(y);
// loop 1 time, as there is 1 item
for (var i = 0; i < myArr.length; i++) {
// set index 0 of the array to a new array with the y input of "2"
myArr[i] = new Array(y);
}
這myArr是一個二維數組而不是一維數組,因為您將數組包裝在一個數組中:
myArr = [
[
"2"
]
]
添加回答
舉報
0/150
提交
取消