使用 for 循环在 JavaScript 中填充二维数组
因此,我需要在 JavaScript 中填充一个二维数组,我按照以下方式执行此操作:
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");
问题是它不仅不起作用,而且它后面的任何代码都不会执行。在本例中为 alert("Hello world");
。我做错了什么,伙计们?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更改
为
change
to
您不需要在循环之前声明
i
和j
。如果它们的存在只是为了循环,那么它们最好作为局部变量。此外,您还可以组合循环。另外,@Yuriy Zubarev 说的是对的。 for 循环中的中间语句是在整个循环中必须保持为真的条件。
You don't need to declare
i
andj
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.看看这个小提琴。
改变你
的
Have a look at this fiddle.
change your
to
您可以使用一个小的辅助函数来简化您的代码
您的代码:
You can simplify your code by using a small helper function
Your code: