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

标签 javascript arrays multidimensional-array

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

  1. 单个xy坐标对

    [x,y]
    
  2. xy 坐标对数组

    [[x,y],[x,y],...]
    
  3. 由 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/

相关文章:

c++ - Ruby 中的多维数组类似于 C++

php - 在 php 中使用多维数组和对象

arrays - 使用 if-else 语句遍历数组 (Swift)

arrays - 使用循环查找特定数组

multidimensional-array - AWK 中的数据透视表

python - python中的多维卷积

javascript - 将单个数据字符串从操作传递到组件 React/Redux/ES6 的最佳方式

javascript - 从 jquery 对话框调用服务器端方法

javascript - 问题: The whole page loading instead just the div with .加载()

javascript - 使用 jQuery 清除动态加载元素的innerHTML