对于大学来说,我们有一个关于二维数组的问题需要解决,但是它们的性质从未在课堂上讨论过。我已经在这个网站上搜索答案(这可能在我的代码中很明显),但无法让它工作,甚至无法真正理解正在发生的事情或原因。确切的问题是:
Write a program that utilises a 8x8 2-dimensional array.
(a) Initialise the array elements via nested for loops as follows
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
...
...
57 58 59 60 61 62 63 64
(b) Add some code that will display all array elements in an 8x8 HTML table.
(c) Use nested for loops for calculating the sum and the average of the
values stored in the array.
Let a function display these values on screen eg use alert().
到目前为止我的代码是:
x = matrix( 8 , 8, 0 ); // 8 lines, 8 cols filled with empty string
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
var add = 1
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue + add;
}
var add = add + 1
}
return arr;
}
function displayInDiv() {
var output_string_ = "" ;
var lastElement = 64 ;
output_string_ = output_string_
+'<table>'
+'<tr>'
+'<th width="11%" align="left">ARRAY INDEX</th>'
+'<th width="11%" align="right"> array_1</th>'
+'<th width="11%" align="right"> array_2</th>'
+'<th width="11%" align="right"> array_3</th>'
+'<th width="11%" align="right"> array_4</th>'
+'<th width="11%" align="right"> array_5</th>'
+'<th width="11%" align="right"> array_6</th>'
+'<th width="11%" align="right"> array_7</th>'
+'<th width="11%" align="right"> array_8</th>'
+'</tr>'
;
for ( var i = 1 ; i < 9 ; i++ ) {
for ( var j = 0 ; j < 7 ; j++ ) {
output_string_ = output_string_
+'<tr id="table_row_'
+ i
+'">'
+'<td width="11%" align="left">'
+'['
+ i
+']'
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'</tr>'
;
}
output_string_ = output_string_
+'<table>'
;
var output_section_ = document.getElementById("list_");
output_section_.innerHTML = output_string_ ;
}
}
抱歉,大量的文本转储,但我完全被难住了。任何帮助将不胜感激。
我相信您正在寻找的确切代码是这样的
var outer = new Array();
for(var i = 0; i < 8; i++) {
var inner = new Array
for(var j = 0; j < 8; j++) {
inner[j] = (i * 8) + j + 1;
}
outer[i] = inner;
}
console.log(outer);
二维数组只是数组的数组,这里我将它们标记为内部和外部。
有 8 个长度为 8 的内部数组,总共有 64 个条目。每个条目的值是 8 * 外部索引(从 0 开始),加上内部索引加 1(因为它也是从 0 开始)。
这应该为您提供足够的信息来回答部分问题b
and c
您自己,但如果您需要进一步的帮助,请随时在下面发表评论。 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)