简体   繁体   English

如何在单个for循环中覆盖网格中的每个正方形?

[英]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.

相关问题 如何在php循环中为网格中的每个帖子运行jquery(wordpress) - How to run jquery in php loop for every post in a grid (wordpress) 如何在测试权限覆盖循环内的语句 - How to cover statements inside a loop in test coeverage 如何在方形网格中查找具有单元格编号的坐标 - How to find coordinates with cell number in a square grid 如何使用 HTML、CSS 和 JS 用网格(可点击的方块)覆盖图像? - How to cover an image with a grid (clickable squares) using HTML, CSS, and JS? 如何在for循环后返回单个诺言,其中循环内数组的每个元素都进行多次异步调用 - How to return a single promise after for loop where every element of an array inside loop do multi async calls 如何让单个WMS磁贴覆盖整个Google Map? - How to get a single WMS tile to cover entire Google Map? 如何更改循环以反转 javascript 中的方形打印 - How to change the loop to reverse the square print in javascript JavaScript 过滤器循环控制。 我如何处理每一个元素? - JavaScript filter loop control. How can I handle every single element? 如何在for循环之后返回单个promise(在每次迭代时产生一个promise)是否完成? - How to return single promise after for loop (which produces a promise on every iteration) is complete? 我怎样才能 select 一个正方形的单元格(任何大小)并捕捉到网格? - How can I select a square of cells (any size) and snap to grid?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM