Getting "typeError" "is not a function" when using .length

Here is my code:

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 codeHide result

If I replace:

return (permutationsFinal);

by:

return (permutationsFinal.length);

I get this error in the console:

TypeError: permAlonenot a function

Why?

Thank you for your help!:)

+4
source share
2 answers

This is a recursive function, if you return something other than expected by the function itself, then you will break the recursive loop.

+3
source

To remove a response from a comment:

for (var subPermutation of permAlone(remainingString))iterates over the return value of a function (called recursively). This is the error line number. Numbers are not repeated, so when you return a number instead of an array, it throws an error.

, , FireFox

TypeError: permAlone (...)

. , , , , , .

+3

Source: https://habr.com/ru/post/1680262/


All Articles