我想使用递归函数反转字符串。问题是为什么这个函数会返回undefined
?
const reverse = function(str) {
const looper = function(str, index) {
if (index < 0) {
return '';
}
return str[index] + looper(str, index - 1);
};
looper(str, str.length - 1);
};
console.log(reverse('Hello World!'));
&#13;
答案 0 :(得分:5)
您需要将return语句添加到主函数
const reverse = function(str) {
const looper = function(str, index) {
if(index < 0) {
return '';
}
return str[index] + looper(str, index - 1);
};
return looper(str, str.length - 1);
};
console.log(reverse('Hello World!'));
答案 1 :(得分:1)
以下是使用解构
的另一种方法
const reverse = ([x,...xs]) =>
x === undefined
? ''
: reverse (xs) + x
console.log (reverse ('hello world'))
// 'dlrow olleh'
console.log (reverse (''))
// ''
&#13;
现在有一个尾调用
const reverse = ([x,...xs], k = x => x) =>
x === undefined
? k ('')
: reverse (xs, next =>
k (next + x))
console.log (reverse ('hello world'))
// 'dlrow olleh'
console.log (reverse (''))
// ''
&#13;
现在我们不做解构
const reverse = xs =>
xs.length === 0
? ''
: reverse (xs.slice (1)) + xs.slice (0,1)
console.log (reverse ('hello world'))
// 'dlrow olleh'
console.log (reverse (''))
// ''
&#13;
这是一个尾调用
const reverse = (xs, k = x => x) =>
xs.length === 0
? k ('')
: reverse (xs.slice (1), next =>
k (next + xs.slice (0,1)))
console.log (reverse ('hello world'))
// 'dlrow olleh'
console.log (reverse (''))
// ''
&#13;
有些人更喜欢.substr
而不是.slice
和.concat
而不是+
- 它取决于您
const reverse = (xs, k = x => x) =>
xs.length === 0
? k ('')
: reverse (xs.substr (1), next =>
k (next.concat (xs.substr (0,1))))
console.log (reverse ('hello world'))
// 'dlrow olleh'
console.log (reverse (''))
// ''
&#13;