Reputation: 3
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
Upvotes: 0
Views: 32
Reputation: 455
There are multiple problems with your code.
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]
}
Upvotes: 1