使用 .length 时获取“typeError”“不是函数”

Emi*_*lio 5 javascript

这是我的代码:

function permAlone(string) {
  if (string.length < 2) return string; // This is our break condition

  var permutations = []; // This array will hold our permutations

  for (var i = 0; i < string.length; i++) {
    var character = string[i];

    // Cause we don't want any duplicates:
    if (string.indexOf(character) != i) // if char was used already
      continue; // skip it this time

    var remainingString = string.slice(0, i) + string.slice(i + 1, string.length); //Note: you can concat Strings via '+' in JS

    for (var subPermutation of permAlone(remainingString))
      permutations.push(character + subPermutation);

  }

  var permutationsFinal = [];
  for (var j = 0; j < (permutations.length); j++) {
    if (!(permutations[j].match(/([a-zA-Z])\1/))) {
      permutationsFinal.push(permutations[j]);
    }
  }

  return (permutationsFinal.length);
  //                       ^^^^^^^^ if I add this, the error is thrown
}

permAlone('abc');
Run Code Online (Sandbox Code Playgroud)

如果我更换:

return (permutationsFinal);
Run Code Online (Sandbox Code Playgroud)

经过:

return (permutationsFinal.length);
Run Code Online (Sandbox Code Playgroud)

我在控制台中收到此错误:

类型错误:permAlone不是函数

为什么?

谢谢你的帮助!:)

小智 3

它是一个递归函数,如果您返回函数本身预期之外的任何内容,那么您将打破递归循环。