我在
JavaScript框架中使用一个函数,其中返回值可以是以下任何一个
>一个xy坐标对
- [x,y]
>一组xy坐标对
- [[x,y],[x,...]
> xy坐标对的数组数组
- [[[x,y]],[[x,...]
返回值取决于对象的几何形状(单点,线或多行).无论返回值及其数组深度如何,我都想获取第一个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));