这个递归 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"
,执行步骤如下:
- 勾选
'abc' == ''
==> false
.
- 创建
substr = 'bc'
.
- 调用
length('bc')
:
- 勾选
'bc' == ''
==> false
.
- 创建
substr = 'c'
.
- 调用
length('c')
:
- 检查
'c' == ''
===> false
.
- 创建
substr = ''
.
- 调用
length('')
:
- 检查
'' == ''
===> true
- Return
0
.
- 运行
0 + 1
.
- Returns
1
.
- 运行
1 + 1
.
- Return
2
.
- 运行
2 + 1
.
- 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
需要一些帮助。
函数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"
,执行步骤如下:
- 勾选
'abc' == ''
==>false
. - 创建
substr = 'bc'
. - 调用
length('bc')
:- 勾选
'bc' == ''
==>false
. - 创建
substr = 'c'
. - 调用
length('c')
:- 检查
'c' == ''
===>false
. - 创建
substr = ''
. - 调用
length('')
:- 检查
'' == ''
===>true
- Return
0
.
- 检查
- 运行
0 + 1
. - Returns
1
.
- 检查
- 运行
1 + 1
. - Return
2
.
- 勾选
- 运行
2 + 1
. - 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