0

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);
Jessica
  • 179
  • 1
  • 5
  • 15
  • 3
    How do you get the user input ? A table with elements ? – tomdemuyt Oct 30 '13 at 15:56
  • You are you trying to achieve with it? – Sorter Oct 30 '13 at 15:57
  • use var b=[] to create array instead b = new Array( 3 ); and when you need to add something in array do this b.push([2,2,3]); – Max Oct 30 '13 at 15:58
  • If you want an ugly JS-only prompt yout can use `prompt("Please enter your name","");`. In fact you already created a 2D array in your code. -- See also: http://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript – Smamatti Oct 30 '13 at 15:58
  • I need to display a window prompt to get user input, then display the elements in a 3x3 table as the user inputs them – Jessica Oct 30 '13 at 16:01

2 Answers2

1

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, i.e.

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.

Community
  • 1
  • 1
Alex Walker
  • 2,337
  • 1
  • 17
  • 32
0

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

JiminP
  • 2,136
  • 19
  • 26