Steamroller JavaScript代码如何发生

发布于 2025-01-26 14:11:20 字数 391 浏览 2 评论 0原文

愉悦描述我递归功能如何在最终结果中弄平阵列。主要请在“如果”部分中描述

function steamrollArray(arr) {
  let answer = [].concat(...arr);
  console.log(answer)
  if(answer.some(Array.isArray)){
    return steamrollArray(answer);
  }
  return answer
}

let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)

pleases describe me recursion function how to happen flatten array in the final result. Mainly please describe in the if section

function steamrollArray(arr) {
  let answer = [].concat(...arr);
  console.log(answer)
  if(answer.some(Array.isArray)){
    return steamrollArray(answer);
  }
  return answer
}

let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与他有关 2025-02-02 14:11:20

添加了console.log,以帮助了解递归的工作原理。引入了变量idx,以帮助跟踪递归级别。

function steamrollArray(arr, idx=0) {
  console.log('bgn--> recursion # ', idx);
  console.log('arr: ', JSON.stringify(arr));
  let answer = [].concat(...arr);
  console.log(
    'computed answer: ', JSON.stringify(answer)
  );
  if(answer.some(Array.isArray)){
    // "answer" has an array, so recurse to next level
    console.log(
      'at least ONE elt in "answer" is an array\n',
      '--> making recursive call from recursion #: ',
      idx
    );
    return steamrollArray(answer, idx+1);
  };
  console.log(
    'no elt in "answer" is an array\n',
    'no more recursion from recursion #: ', idx,
    ' answer: ', answer.join(),
    ' has ZERO arrays ...'
  );
  return answer;
}

let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0 }

Have added console.log to help with understanding how the recursion works. Introduced a variable idx to help track the level of recursion.

function steamrollArray(arr, idx=0) {
  console.log('bgn--> recursion # ', idx);
  console.log('arr: ', JSON.stringify(arr));
  let answer = [].concat(...arr);
  console.log(
    'computed answer: ', JSON.stringify(answer)
  );
  if(answer.some(Array.isArray)){
    // "answer" has an array, so recurse to next level
    console.log(
      'at least ONE elt in "answer" is an array\n',
      '--> making recursive call from recursion #: ',
      idx
    );
    return steamrollArray(answer, idx+1);
  };
  console.log(
    'no elt in "answer" is an array\n',
    'no more recursion from recursion #: ', idx,
    ' answer: ', answer.join(),
    ' has ZERO arrays ...'
  );
  return answer;
}

let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0 }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文