获取可变深度数组中的第一个数字数组

Jel*_*tor 7 javascript arrays multidimensional-array

我在JavaScript框架中使用一个函数,其中返回值可以是以下任何一个

  1. 一个xy坐标对

    [x,y]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 一组xy坐标对

    [[x,y],[x,y],...]
    
    Run Code Online (Sandbox Code Playgroud)
  3. xy坐标对的数组数组

    [[[x,y],[x,y]],[[x,y],[x,y]],...]
    
    Run Code Online (Sandbox Code Playgroud)

返回值取决于对象的几何形状(单点,线或多行).无论返回值及其数组深度如何,我都想获取第一个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];
}
Run Code Online (Sandbox Code Playgroud)

我真的很讨厌这个解决方案,我正在寻找更优雅的东西.

Red*_*edu 4

我想在纯 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));
Run Code Online (Sandbox Code Playgroud)