Skip to content

数组嵌套转换:

示例2: 输入 [1,[2,[3,[4,5,6]]]] 输出 [6,[5,[4,[3,2,1]]]]

js
function reverseNestedArray(arr) {
  // 1. 提取所有数字到一个扁平数组中
  const flatArray = [];
  function flatten(currentArr) {
    for (const item of currentArr) {
      if (Array.isArray(item)) {
        flatten(item);
      } else {
        flatArray.push(item);
      }
    }
  }
  flatten(arr);

  // 2. 反转扁平数组
  flatArray.reverse();

  // 3. 将反转后的数字填充回原始结构
  let index = 0;
  function reconstruct(currentArr) {
    return currentArr.map(item => {
      if (Array.isArray(item)) {
        return reconstruct(item);
      } else {
        // 从反转后的数组中按顺序取出元素进行填充
        return flatArray[index++];
      }
    });
  }

  return reconstruct(arr);
}

// 示例
const input = [1, [2, [3, [4, 5, 6]]]];
const output = reverseNestedArray(input);

console.log(JSON.stringify(output)); // 输出: [6,[5,[4,[3,2,1]]]]
本站访客数 人次 本站总访问量