Home > database >  Array.push() is not a function - attempting to push numbers to an array, but the array has changed t
Array.push() is not a function - attempting to push numbers to an array, but the array has changed t

Time:01-21

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.

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • Related