federicot
federicot

Reputation: 12341

Filling a bi-dimensional array in JavaScript using a for loop

So, I need to fill a bi-dimensional array in JavaScript and I'm doing it the following way:

var i = 0, j = 0;
for (i = 0; i < roomWidth / tileWidth; i += 1) {
     roomBuffer[i] = [];
}
for (i = 0; roomWidth / tileWidth; i += 1) {
     for (j = 0; j < roomHeight / tileHeight; j += 1) {
          roomBuffer[i][j] = 1;
     }
}
alert("Hello world");

The problem is that it not only doesn't work but any code that comes after it, it's not executed. In this case the alert("Hello world");. What am I doing wrong guys?

Upvotes: 2

Views: 595

Answers (4)

georg
georg

Reputation: 214949

You can simplify your code by using a small helper function

// create an array of length len filled with value
fill = function(len, value) {
    for (var a = []; len-- > 0; a.push(value));
    return a;
}

Your code:

size = roomWidth / tileWidth
roomBuffer = fill(size, fill(size, 1))    

Upvotes: 0

hrishikeshp19
hrishikeshp19

Reputation: 9028

Have a look at this fiddle.

change your

for (i = 0; roomWidth / tileWidth; i += 1)

to

for (i = 0; i < roomWidth / tileWidth; i += 1)

Upvotes: 1

chharvey
chharvey

Reputation: 9326

You don't need to declare i and j before the loops. If their existence is solely for the loops, they are better off as local variables. Also, you can combine loops.

Also, what @Yuriy Zubarev said is right. The middle statement in the for-loop is a condition that must hold true throughout the loop.

for (var i = 0; i < roomWidth / tileWidth; i++) {
     roomBuffer[i] = [];
     for (var j = 0; j < roomHeight / tileHeight; j++) {
          roomBuffer[i][j] = 1;
     }
}
alert("Hello world");

Upvotes: 1

Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

change

for (i = 0; roomWidth / tileWidth; i += 1) {

to

for (i = 0; i < roomWidth / tileWidth; i += 1) {

Upvotes: 4

Related Questions