Javascript反向功能麻烦

时间:2017-10-31 20:22:03

标签: javascript function recursion

我想使用递归函数反转字符串。问题是为什么这个函数会返回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;
&#13;
&#13;

2 个答案:

答案 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)

以下是使用解构

的另一种方法

&#13;
&#13;
const reverse = ([x,...xs]) =>
  x === undefined
    ? ''
    : reverse (xs) + x

console.log (reverse ('hello world'))
// 'dlrow olleh'

console.log (reverse (''))
// ''
&#13;
&#13;
&#13;

现在有一个尾调用

&#13;
&#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;
&#13;
&#13;

现在我们不做解构

&#13;
&#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;
&#13;
&#13;

这是一个尾调用

&#13;
&#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;
&#13;
&#13;

有些人更喜欢.substr而不是.slice.concat而不是+ - 它取决于您

&#13;
&#13;
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;
&#13;
&#13;