Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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');

If I replace:

return (permutationsFinal);

by:

return (permutationsFinal.length);

I get this error in the console:

TypeError: permAlone is not a function

Why?

Thanks for your help! :)

like image 662
Emilio Avatar asked Jun 28 '17 03:06

Emilio


People also ask

How do I fix TypeError is not a function?

The TypeError: "x" is not a function can be fixed using the following suggestions: Paying attention to detail in code and minimizing typos. Importing the correct and relevant script libraries used in code. Making sure the called property of an object is actually a function.

What does .length mean in Javascript?

The length property of an Array object represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

What does .length do in an array?

The length property sets or returns the number of elements in an array.

Is .length and .length 0 the same?

length can only be 0 or larger and since 0 is the only number that evaluates to false , there is no difference.


1 Answers

It is a recursive function, if you return anything other than what is expected by the function itself then you will break the recursive loop.

like image 76
aduss Avatar answered Oct 06 '22 00:10

aduss