简体   繁体   中英

Creating a 2d Array Javascript

How can I create a 2d array in javascript and load it with the values from user input?

var b;
b = new Array( 3 ); // allocate rows
b[ 0 ] = new Array( 3 ); // allocate columns for row 0
b[ 1 ] = new Array( 3 ); // allocate columns for row 1
b[2]= new Array(3);

How to create a 2D array: How can I create a two dimensional array in JavaScript?

Loading values from user input: essentially use

b[0][0] = myInput00;
b[0][1] = myInput01;

...etc. etc.

It may be more structured to use for-loops, ie

for (var i=0;i<input.length;i++)
{ 
    for (var j = 0; j < input.height; j++)
    {
        b[i][j] = input[i][j];
    }
}

with input[i][j] replaced with however your input is formatted. The answer clearly varies slightly depending on the input format, but that's the general pattern.

Edit: if the input is a fixed 3x3 box, you might just assign all the table cells as individual divs or spans, and allocate each of the array indices (b[0][0], b[0][1] etc.) in turn.

Multi-dimensional arrays in many languages are just arrays within arrays.

// Create an array with 4 elements.
var b = [1, [2, 3], [4, [5, 6], 7], 8];
console.log(b.length); // 4

// Looping through arrays
for(var i=0; i<b.length; i++){
  // b[0] = 1
  // b[1] = [2, 3]
  // b[2] = [4, Array[2], 7]
  // b[3] = 8
  console.log("b["+i+"] =", b[i]);
}

// Since b[1] is an array, ...
console.log(b[1][0]); // First element in [2, 3], which is 2

// We can go deeper.
console.log(b[2][1]); // [5, 6]
console.log(b[2][1][0]); // 5

// We can change entries, of course.
b[2][1][0] = 42;
console.log(b[2][1][0]); // 42

b[1] = ['a', 'b', 'c'];
console.log(b[1][0]); // "a"

Therefore, making a 3 by 3 matrix can be done like this:

var b = [];
for(var i=0; i<3; i++){
  b[i] = [];
  for(var j=0; j<3; j++){
    b[i][j] = prompt("b["+(i+1)+","+(j+1)+"] = ?");
  }
}

(Of course, this is not the best way to do, but it is the easiest way to follow.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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