SoFunction
Updated on 2025-03-01

Example of JS implementation of horizontal traversal and nested recursive operations

This article describes the implementation of horizontal traversal and nested recursive operations in JS. Share it for your reference, as follows:

There are some interesting logic in the program, such as multi-layer nesting can be traversed recursively, such as if else on the same layer can be traversed with arrays.

Here is an example. If a multi-layer nested if else needs to be recursively traversed, you need to write the following form, and recursive traversed with a specific form:

Multi-layer nested function transliterated by if else

let p1 = false,
p2 = true,
p3 = false;
let test = function() {
    if (p1) {
      return 'Terminate 1';
    } else {
      return function() {
        if (p2) {
          return 'Terminate 2'
        } else {
          return function() {
            if (p3) {
              return 'Termination 3'
            }
          }
        }
      }
    }
}

Traversal of multi-layer nesting:

function yunxing1() {
    while (test()) {
      test = test()
      if (typeof test === 'string') {
        alert(test)
        return 'termination'
      }
    }
}
yunxing1()

Functions and traversal methods rewritten by multiple if else on the same layer

let i = 1,
a = 2,
b = 3;
function simpleVlidate() {
    let varr = [];
    (() => {
      if (i === 1) {
        return 'Can't equal 1'
      }
    })
    (() => {
      if (a === 2) {
        return 'Can't equal 2'
      }
    })
    (() => {
      if (b === 3) {
        return 'Can't equal 3'
      }
    })
    return varr
}
let arrs = simpleVlidate();
function yunxing() {
    for (let i = 0, fn; fn = arrs[i++];) {
      if (fn()) {
        alert(fn())
        return;
      }
    }
    (343433333333)
}
yunxing();

The above, the interesting logic summarized is also a way to simplify the code. There is still a lot of logic like this...

PS: Here I recommend a JS array traversal method analysis and comparison tool for your reference:

Performance analysis and comparison tool for common online JS traversal methodshttp://tools./aideddesign/js_bianli

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript array operation skills》、《JavaScript traversal algorithm and skills summary》、《JavaScript object-oriented tutorial》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript data structure and algorithm techniques"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.