这个递归 Javascript 函数是如何工作的(返回字符串的长度)

How does this recursive Javascript function works (Returning the length of a string)

需要一些帮助。

函数returns递归字符串的长度

const length = str => str == '' ? 0 : length(str.substring(1)) + 1;

它工作正常。我很难理解 length(str.substring(1)) + 1 部分的返回是如何工作的。一切如何加起来?例如输入:"Hello World" 输出:11. 为什么函数不连接(因为“+”符号)输入:"Hello World" 输出:"Hello World11"?

谢谢

为了简化解释,我将函数重写为下面的 "long form":

function length(str){
  if (str == ''){
    return 0;
  }
  const substr = str.substring(1);
  return length(substr) + 1;
}

console.log(length('abc'));

所以给定输入"abc",执行步骤如下:

  1. 勾选'abc' == '' ==> false.
  2. 创建substr = 'bc'.
  3. 调用length('bc')
    1. 勾选'bc' == '' ==> false.
    2. 创建substr = 'c'.
    3. 调用length('c')
      1. 检查'c' == '' ===> false.
      2. 创建substr = ''.
      3. 调用length('')
        1. 检查'' == '' ===> true
        2. Return 0.
      4. 运行0 + 1.
      5. Returns 1.
    4. 运行1 + 1.
    5. Return 2.
  4. 运行2 + 1.
  5. Return 3.

如您所见,代码中没有任何地方会导致字符串与数字的连接。

例如 海峡 = "hello" ,执行代码"length(str)" 步骤如下

    length("hello")
    length("ello") + 1 
    (length("ll") + 1) + 1
    ((length("lo") + 1) + 1) + 1
    (((length("o")+1) + 1) + 1) + 1
    ((((0 + 1)+1) + 1) + 1) + 1