-2

I'm 3 months into Javascript, and find it has no respect for its own declarations.

I have declared an empty array, and want to push a number to it, so that it returns an array of numbers (i.e., separable). However, I am told .push() is not a function. Concat() will not work either, and of course += ruins the algorithm.

How do I get it to accept each next value into an array? I have tried using 'new Array()', but it does not assist.

Similar to, but not the same as, Array.push throwing TypeError for array.push is not a function

In brief:

const fn = (n) => {
  let factors = [];
  let index = 1;

  while (n % 2 == 0){
    let out = 2 ** index;
    factors.push(out);
    index++;
    n /= 2;
  }
}

This returns:

Uncaught TypeError: factors.push is not a function

(I have left out a lot of code that does not affect the issue.)

Edit update: WIP. Apparently, the loop this is enclosed in has an effect, as do other variable declarations.

With any luck, I will return with a different question, having solved the initial problem.

1
  • The problem could not be found with this code. Commented Jan 20, 2022 at 8:17

2 Answers 2

0

Nested loops seems to have been the actual problem, which means others could not reproduce.

const fn = (m, n) => {
let factors = [];
let index = 1;
for (let i = m; i <= n; i++) {
while (i % 2 == 0){
  let out = 2 ** index;
  factors.push(out);
  index++;
  n /= 2;
  } 
}}

For unknown reasons, this causes a type mismatch. The declaration of the array appears to be the cause.

This problem has been abandoned as the initiating function was completed by other methods.

Sign up to request clarification or add additional context in comments.

Comments

-1

Here! its working well, what might went wrong on your side?

const fn = (n) => {
  let index = 1;
  let factors = [];
  while (n % 2 == 0){
    let out = 2 ** index;
    factors.push(out);
    index++;
    n /= 2;
  }
  return factors
}


 document.write(fn(400));

3 Comments

This reads more like a game of spot-the-difference than an answer. Why should the changes you made solve push not being a function? I couldn’t reproduce the issue in the first place, and your changes seem of take place only after the call to push that the OP says doesn’t work.
I have discovered that apparently, wrapping it all in a for() loop makes a difference. I do not understand why, but I believe I shall edit the question.
However, since I'm getting a different error by only wrapping it in a for loop, we'll call that progress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.