問題描述
我正在使用 Leafletjs 在 openstretmap 上顯示一些多邊形.
I'm using leafletjs to display some polygons on an openstretmap.
我有一個外部數據資源,它為我提供了多邊形的坐標.不幸的是,這個數組的坐標順序錯誤.
I have an external data ressource which gives me the coordinates for the polygons. Unfortunately this array has the wrong order for the coordinates.
示例:我明白了:
[[10.5254913,52.2734311],[10.5258872,52.2734632]]
[[10.5254913,52.2734311],[10.5258872,52.2734632]]
我需要:
[[52.2734311,10.5254913],[52.2734632,10.5258872]]
[[52.2734311,10.5254913],[52.2734632,10.5258872]]
所以我給自己寫了一個小函數,它遍歷數組并反轉條目:
So I wrote myself a little function which iterates through the array and reverses the entries:
var polCoords = [];
$.each(value.polygon[0], function(key,value){
polCoords[key] = [value[1],value[0]];
});
這很好用.但是現在我發現多邊形的一些數組是多維的!所以我有一個這樣的數組:
This works just fine. But now I discovered that some arrays for the polygons are multidimensional! So I have an array like this:
[[[10.5261828,52.2726556],[10.5263222,52.2726767],[10.5263578,52.2726821],[10.5263637,52.2726677],[10.5263738,52.2726428],[10.5264042,52.2725678],[10.526186,52.2725346],[10.5261395,52.272649],[10.5261828,52.2726556]],[[10.5261828,52.2726556],[10.5261713,52.2726821],[10.5261621,52.2727047],[10.5259248,52.2726687],[10.5257879,52.2726479],[10.5257435,52.2727573],[10.5258014,52.2727661],[10.5257967,52.2727777],[10.5260173,52.2728113],[10.5261107,52.2728254],[10.5260641,52.2729403],[10.5259711,52.2729262],[10.5259526,52.2729234],[10.5258101,52.2732746],[10.5258697,52.2732837],[10.5260636,52.2733132],[10.5261371,52.2733243],[10.5262746,52.2729854],[10.5262888,52.2729876],[10.526312,52.2729304],[10.5262636,52.2729231],[10.5262239,52.272917],[10.5263222,52.2726767],[10.5261828,52.2726556]],[[10.5260636,52.2733132],[10.5260595,52.2733365],[10.5260575,52.2733486],[10.5258607,52.2733326],[10.5258631,52.2733195],[10.5258697,52.2732837],[10.5260636,52.2733132]]]
它似乎由多個多邊形組成.
Which seems to consist of more than one polygon.
如何反轉這個多維數組的每個條目?
How can I reverse every entry of this multidimensional array?
推薦答案
假設 array
是您的數據,嘗試類似:
Assuming array
is your data, try something like:
var reversed = array.map(function reverse(item) {
return Array.isArray(item) && Array.isArray(item[0])
? item.map(reverse)
: item.reverse();
});
這是普通的 JavaScript.我認為在 jquery 中會是這樣的:
This is vanilla JavaScript. I think in jquery would be something like:
var reversed = $.map(array, function reverse(item) {
return $.isArray(item) && $.isArray(item[0])
? $.map(item, reverse)
: item.reverse();
});
我沒有嘗試,但應該可以同時使用它們.告訴我.
I didn't try but should works both of them. Let me know.
這篇關于javascript中(多維)數組中的反向條目的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!