假设我们像这样排列数组-
const arr = [ [-73.9280684530257, 40.8099975343718], [-73.9282820374729, 40.8100875554645], [-73.9280124002104, 40.8103130893677], [-73.927875543761, 40.8102554080229], [-73.9280684530257, 40.8099975343718] ];
在这里,每个子数组代表二维平面上的一个点,每个点都是n边多边形的顶点,其中n是输入数组中子数组的数量。
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并返回n个子数组的新数组,每个子数组代表多边形对应边的中点。
为此的代码将是-
const arr = [ [-73.9280684530257, 40.8099975343718], [-73.9282820374729, 40.8100875554645], [-73.9280124002104, 40.8103130893677], [-73.927875543761, 40.8102554080229], [-73.9280684530257, 40.8099975343718] ]; const findCenters = arr => { const centerArray = []; for(i = 0; i<arr.length; i++){ nextIndex = (i+1) % (arr.length); centerArray[i] = []; centerArray[i][0] = (arr [i][0] + arr[nextIndex][0]) / 2; centerArray[i][1] = (arr[i][1] + arr[nextIndex][1]) / 2; }; return centerArray; }; console.log(findCenters(arr));
输出结果
控制台中的输出-
[ [ -73.92817524524929, 40.81004254491815 ], [ -73.92814721884164, 40.8102003224161 ], [ -73.92794397198571, 40.8102842486953 ], [ -73.92797199839336, 40.81012647119735 ], [ -73.9280684530257, 40.8099975343718 ] ]