Sebastiaan de Bruin Sebastiaan de Bruin - 1 month ago 22
Javascript Question

numerically populating a 2d array

Javascript is new to me so I'm trying to learn. Mostly with unstable succes-rates...

In this case, I would like to populate a 2D array with a double for loop, but the code is not running properly. Could somebody point out the problem in the code or help me to fix it?

the code is:

function 2d_array(){

var x = 2;
var y = 3
var A = [1,2,3];
var B = [4,5,6];
var z = [][];

for (var i = 0; i < 3; i++){
for (var j = 0; j < 3; j++){
z[i][j]=x*A[i] + y*B[j];
}
}
return z[1][1]
}


It would really help me out alot. Thanks, Bas

Answer

There are multiple problems with your code.

  1. Function names must begin with a letter
  2. var z=[][]; is incorrect syntax.

This should work:

function array_2d() {

  var x = 2;
  var y = 3
  var A = [1, 2, 3];
  var B = [4, 5, 6];
  var z = [];

  for (var i = 0; i < 3; i++) {
    z[i] = [];
    for (var j = 0; j < 3; j++) {
      z[i][j] = x * A[i] + y * B[j];
    }
  }
  return z[1][1]
}