我在 JavaScript 框架中使用一个函数,它的返回值可以是以下的任何
单个xy坐标对
[x,y]
xy 坐标对数组
[[x,y],[x,y],...]
由 xy 坐标对组成的数组
[[[x,y],[x,y]],[[x,y],[x,y]],...]
返回值取决于对象的几何形状(单点、线或多线)。不管返回值和它的数组深度如何,我想抓取第一个xy坐标对。执行此操作的有效方法是什么?
到目前为止,这是我实现目标的代码:
//here is the magic method that can return one of three things :)
var mysteryCoordinates = geometry.getCoordinates();
var firstCoord;
if(typeof mysteryCoordinates[0] === 'number') {
firstCoord = mysteryCoordinates;
} else if (typeof mysteryCoordinates[0][0] === 'number') {
firstCoord = mysteryCoordinates[0];
} else if (typeof mysteryCoordinates[0][0][0] === 'number') {
firstCoord = mysteryCoordinates[0][0];
}
我真的很讨厌这个解决方案,正在寻找更优雅的东西。
最佳答案
我想在纯 JS 中应该这样做;
var arr = [[[1,2],[1,3]],[[4,8],[3,9]]],
getFirstXY = a => Array.isArray(a[0]) ? getFirstXY(a[0]) : a;
console.log(getFirstXY(arr));
关于javascript - 获取可变深度数组中的第一个数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39755331/