简体   繁体   English

Javascript中的2D数组

[英]2D Arrays in Javascript

For college, we have a problem to solve regarding 2D arrays, however the nature of them has never been cover in class. 对于大学来说,我们在2D阵列方面有一个问题需要解决,但是它们的性质从未在课堂上得到覆盖。 I've scoured this site for answers(which might be evident in my code) but cannot get it to work, or even truly understand what is going on or why. 我已经搜索了这个网站的答案(这可能在我的代码中很明显),但无法让它工作,甚至无法真正理解发生了什么或为什么。 The exact question is: 确切的问题是:

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().   

The code I have so far is : 我到目前为止的代码是:

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_ ; 

}
}

Sorry for the huge text dump, but i'm completely stumped. 抱歉,巨大的文本转储,但我完全难倒。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I believe the exact code you're looking for is this 我相信你正在寻找的确切代码就是这个

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);

A 2D array is just an array of arrays, here I labelled them inner and outer. 2D数组只是一个数组数组,在这里我将它们标记为内部和外部。

There are 8 inner arrays of length 8, giving you 64 total entries. 有8个长度为8的内部数组,总共有64个条目。 The value of each entry is 8 * the outer index (which starts at 0), plus the inner index plus 1 (because it also starts at 0). 每个条目的值是8 *外部索引(从0开始),加上内部索引加1(因为它也从0开始)。

This should give you enough information to answer parts b and c yourself, but feel free to comment below if you'd like further help. 这应该为您提供足够的信息来自己回答部分bc ,但如果您需要进一步的帮助,请随时在下面发表评论。 :) :)

answer for (a) 回答(一)

var arr = [];
var value = 0;
for(var i = 0; i < 8; i++){
  var tempArr = [];
  for(var j = 0; j < 8; j++){
    tempArr.push(++value);
  }
  arr.push(tempArr);
}

//`arr` has values initialized with 1 - 64

answer for (b) 回答(二)

   var table = "<table>";

   for(var i = 0; i < 8; i++){
      table += "<tr>";
      for(var j = 0; j < 8; j++){
        table += "<td>" + arr[i][j] + "</td>";
      }
      table += "</tr>";
    }
    table += "</table>";

//assume you have an element with id="tbl" in DOM
document.getElementById("tbl").innerHtml = table;

answer for (c) 回答(c)

 var sum = 0 , avg = 0;
   for(var i = 0; i < 8; i++){          
      for(var j = 0; j < 8; j++){
        sum += arr[i][j];
      }
    }
  avg = sum / 64;

 alert("sum: " + sum + " Average: " + avg);

After you create array you can initialize each of the element with another array. 创建数组后,您可以使用另一个数组初始化每个元素。

var myarray=new Array(8)

for (i=0; i <8; i++)
    myarray[i]=new Array(8)

Hope this helps. 希望这可以帮助。

Cheers ! 干杯!

I made a JSFiddle for this, with comments. 我为此做了一个JSFiddle ,带有评论。

HTML HTML

<button onclick="showCalculations();">Show Calculations!</button>
<div id="container"></div>

JavaScript JavaScript的

//Create the 2-d array
var rows = 8; //Number of rows
var columns = 8; //Number of columns
var list = []; //Array where we will put the data
var index = 0; //Keeps track of which index we're at

for(var i = 0; i < rows; i++){
  var rowList = []; //Create sub-array
  list.push(rowList); //Add the sub-array to our top-level array
  for(var y = 0; y < columns; y++){
    index++; //Increment the index
    rowList.push(index); //Add the index to the current sub-array
  }
}

//Create the Table as HTML string
var table = "<table>"; //Start HTML for table
for(var i = 0; i < list.length; i++){
  var row = list[i];
  table += "<tr>"; //Start HTML for row
  for(var y = 0; y < row.length; y++){
    var column = row[y];
    table += "<td>" + column + "</td>"; //Table cell with content
  }
  table += "</tr>"; //End HTML for row
}
table += "</table>"; //End HTML for table

document.getElementById("container").innerHTML = table; //Find element with id container and set HTML to table

//Calculations
var sum = 0; //Keeps track of the sum
var numberOfNumbers = 0; //Keeps track of how many numbers has been summed

for(var i = 0; i < list.length; i++){
  var row = list[i];
  for(var y = 0; y < row.length; y++){
    var column = row[y];
    sum += column; //Add to sum
    numberOfNumbers++; //Increment amount of numbers
  }
}

var avarage = sum / numberOfNumbers; //Calculate avarage

//Function to alert the values
function showCalculations(){
  alert("Sum: " + sum + "\nAvarage: " + avarage)
}

Note that the creation of the Table and the calculations can be done in the same for-loop . 请注意,表的创建和计算可以在相同的for-loop (Acctually all can be, but then we're not making use of the Array we create). (实际上所有都可以,但是我们没有使用我们创建的数组)。

 var num; var arr = []; // This for loop populates the array for (var i = 0; i <= 7; i++) { arr[i] = []; for (var j = 0; j <= 7; j++) { arr[i][j] = i * 8 + j + 1; } } // This function displays the populated array function displayArr(arr) { var container = document.getElementById("container"); var append = "<table>"; for (var i = 0; i < arr.length; i++) { append += "<tr>"; for (var j = 0; j < arr[i].length; j++) { num = i * 8 + j + 1; append += "<td>" + num + "</td>"; } append += "</tr>"; } container.innerHTML = append; } // Alerts the sum of all numbers in the 2d array function getSum() { var sum = 0; for (var i = 0; i <= 7; i++) { for (var j = 0; j <= 7; j++) { sum += i * 8 + j + 1; } } return sum; } // Alerts the average of all numbers in the 2d array function getAvg() { var totalNumbers = 0; var avg = 0; for (var i = 0; i <= 7; i++) { for (var j = 0; j <= 7; j++) { totalNumbers++; } } return getSum() / totalNumbers; } alert(getAvg()); alert(getSum()); displayArr(arr); 
 <section id="container"></section> 

EDIT* Added the average and sum functions 编辑*添加了平均和求和函数

I correct your code. 我更正你的代码。 Html: HTML:

<button onclick='run()'>Show</button>
<div id='list_'></div>

And js: 和js:

function run() {
  x = matrix( 8 , 8, 0 ); 
  alert(x);
  displayInDiv(x);
}
function matrix( rows, cols, defaultValue){
    var arr = [];
    var number = 1;
    for(var i = 0; i < rows; i++){
        arr.push([]);
        arr[i].push( new Array(cols));
        for(var j=0; j < cols; j++){
            arr[i][j] = number;
            number++;
        }
    }
    return arr;
}

function displayInDiv() {
    var output_string_ = "" ;
    var lastElement = 64 ;
    var output_string_ = '<table>'
    for ( var i = 0 ; i < 8 ; i++ ) { 
        output_string_ += "<tr id='table_row_" + i + "'>";
        for ( var j = 0 ; j < 8 ; j++ ) {
            output_string_ += '<td width="11%" align="left">' + x[i][j] + '</td>';
        }
        output_string_ += '</tr>';
    }
    output_string_ += '</table>';

    var output_section_ = document.getElementById("list_");
    output_section_.innerHTML = output_string_ ; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM