为了获得数组的深度,我以为可以使用flat()方法,如下所示:

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,它将接缝工作,但



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

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

最佳答案

我认为递归方法更简单。如果当前项是数组,请确定其子项的最大深度并加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);

09-06 13:15