[英]How to cover every square in a grid in a single for loop?
I am implementing dynamic map tiles and have come across a bit of a puzzling issue. 我正在实现动态地图图块,并且遇到了一些令人困惑的问题。 Suppose I have a grid of 8x8 squares, like a chessboard.
假设我有一个8x8正方形的网格,就像棋盘一样。 I need to place an image on each of these squares, preferably starting in the centre and working out from there.
我需要在每个正方形上放置一个图像,最好从中心开始并从那里开始。
Is this possible to accomplish in a single for loop, or will it take several loops? 这是否可能在单个for循环中完成,还是需要几个循环? As I said, these images are squares, and are being placed on a map.
如我所说,这些图像是正方形,并被放置在地图上。 They are all 0.025° in latitude/longitude.
它们的经度/纬度均为0.025°。
Here's my initial thought: 这是我最初的想法:
for (var i=-0.25; i<=0.25; i+=0.025) {
var adjustedLatitude = (requestedLatitude + i);
var adjustedLongitude = (requestedLongitude + i);
}
Of course, this will only fill the grid in a diagonal pattern. 当然,这只会以对角线模式填充网格。 What is the best way to do this?
做这个的最好方式是什么?
Personally I think it's most readable to use a nested loop: 我个人认为使用嵌套循环最易读:
for (var i=-0.25; i<=0.25; i+=0.025) {
for (var j=-0.25; j<=0.25; j+=0.025) {
var adjustedLatitude = (requestedLatitude + i);
var adjustedLongitude = (requestedLongitude + j);
doStuffWithAxes(adjustedLatitude, adjustedLongitude);
}
}
However, you could accomplish it using a single loop as so: 但是,您可以这样使用一个循环来完成它:
for (var i=0; i<=20*20; i++) {
var xoffset = (i % 20 - 10) / 40;
var yoffset = (i / 20 - 10) / 40;
var adjustedLatitude = (requestedLatitude + xoffset);
var adjustedLongitude = (requestedLongitude + yoffset);
doStuffWithAxes(adjustedLatitude, adjustedLongitude);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.