在JavaScript中获取数组的深度 [英] Get array's depth in JavaScript

查看:765
本文介绍了在JavaScript中获取数组的深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了获得数组的深度,我想我可以像这样使用flat()方法:

In order to get the array's depth I thought I can use the flat() method like so:

function getArrayDepth(ry){
  // number of levels: how deep is the array
  let levels = 1;
  // previous length
  let prev_length = 1;
  // current length
  let curr_length = ry.length;
  //if the resulting array is longer than the previous one  add a new level
  while(curr_length > prev_length){
  ry = ry.flat();
  prev_length = curr_length
  curr_length = ry.length;
  levels ++
  }
  return levels;
}



let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]

console.log(testRy);

console.log(getArrayDepth(testRy))

console.log(testRy);

如果其中一个数组的长度为1,则表明它可以正常工作

It seams it works BUT if one of the arrays inside has a length of 1

let testRy = [1、2,[3、4,[5、6],7,[8, [9] ],10],11、12]

let testRy = [1, 2, [3, 4, [5, 6], 7, [8, [9] ], 10], 11, 12]

该函数失败,因为展平的数组与上一个数组一样长.

the function fails since the flattened array is as long as the previous one.

有没有更好的方法来获取javascript中数组的深度?

Is there a better way to get the depth of an array in javascript?

推荐答案

我认为递归方法更简单.如果您当前的项目是数组,请确定其子项的最大深度并添加1..

I think a recursive approach is simpler. If your current item is an Array determine the max depth of its children and add 1.

function getArrayDepth(value) {
  return Array.isArray(value) ? 
    1 + Math.max(...value.map(getArrayDepth)) :
    0;
}



let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]

console.log(testRy);

console.log(getArrayDepth(testRy))

console.log(testRy);

这篇关于在JavaScript中获取数组的深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆