【发布时间】:2017-02-06 21:29:56
【问题描述】:
我在 JavaScript 框架中使用一个函数,其中返回值可以是以下 ANY
-
单个 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];
}
我真的很讨厌这种解决方案,并且正在寻找更优雅的解决方案。
【问题讨论】:
-
geometry对象是否没有一些属性可以告诉您它所代表的几何类型,即点、线、线? -
我要获取第一个 xy 坐标对你只对第一对感兴趣吗?或者稍后您可能还想要一些其他索引数据?
-
@PatrickEvans 确实如此,但我必须对几何对象进行三个单独的 typeof 检查才能知道访问第一个坐标对的正确深度。
-
@Reddy 是的,我只对第一对感兴趣。
标签: javascript arrays multidimensional-array