You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套循环转换为递归?附JavaScript代码示例求实现方案

Convert Nested JavaScript Loops to Recursion

Got it, let's break down how to turn that nested loop into recursion step by step. The original code runs an outer loop for i from 0 to 4, and for each i, it runs an inner loop for j from 0 to 4, logging each pair. Here's how to replicate that behavior with recursion, in a couple of straightforward ways:

Method 1: Separate Recursive Functions for Outer and Inner "Loops"

This approach mirrors the original nested loop structure closely by splitting the logic into two recursive functions—one handling the outer i sequence, and the other handling the inner j sequence for each i:

// Inner recursion: handles the j iteration for a given i
function innerRecursion(i, j) {
  // Termination condition: stop when j reaches 5
  if (j >= 5) return;
  
  console.log(i, j);
  // Recurse with j incremented by 1
  innerRecursion(i, j + 1);
}

// Outer recursion: handles the i iteration
function outerRecursion(i) {
  // Termination condition: stop when i reaches 5
  if (i >= 5) return;
  
  // Run the inner recursion for the current i, starting j at 0
  innerRecursion(i, 0);
  // Recurse with i incremented by 1
  outerRecursion(i + 1);
}

// Start the recursion with i=0
outerRecursion(0);

How it works:

  • outerRecursion starts at i=0 and calls innerRecursion to handle all j values for that i.
  • Once innerRecursion finishes (when j >=5), outerRecursion increments i and repeats the process until i >=5.

Method 2: Single Recursive Function for Both Iterations

If you prefer a single function, you can handle both i and j in one place by checking which iteration needs to progress:

function nestedRecursion(i, j) {
  // Terminate the entire process if i has reached 5
  if (i >= 5) return;
  
  if (j < 5) {
    // Still in the inner j loop: log the pair and increment j
    console.log(i, j);
    nestedRecursion(i, j + 1);
  } else {
    // Inner loop done for current i: move to next i, reset j to 0
    nestedRecursion(i + 1, 0);
  }
}

// Start with i=0, j=0
nestedRecursion(0, 0);

How it works:

  • The function first checks if we've exhausted all i values (termination condition).
  • If j is still within bounds, it logs the pair and recurses with j+1.
  • When j hits 5, it switches to the next i and resets j to 0, continuing the recursion.

Both methods will produce exactly the same output as your original nested loop: every pair (0,0) through (4,4) logged in order.

内容的提问来源于stack exchange,提问作者Dhruv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:28:34