Reputation: 12341
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
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
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
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
Reputation: 2871
change
for (i = 0; roomWidth / tileWidth; i += 1) {
to
for (i = 0; i < roomWidth / tileWidth; i += 1) {
Upvotes: 4