2

I'm quite new to javascript and I can't find out at which point an undefined object is inserted into my array:

function foo(arrA){
  if(!arrA || arrA[0] === 0)
       return undefined;

  let arrB = [];
  let prevEntry = 1;

  for(let i=0; i < arrA.length; i++) {
      if (2*prevEntry == arrA[i]) {
          prevEntry *= 2;
          arrB[i] = (Math.pow(arrA[i], 2)).toString();
      }
  }

  return arrB;
}

foo([2,4,6,8,9,15,16,27]);

As output I get an array with powers of 2, as expected, but it's interlaced with undefined objects and I just don't see why.

(7) ["4", "16", undefined × 1, "64", undefined × 2, "256"]

Thanks for your help in advance! :-)

3
  • if means you dont set a value into ArrB at each ArrA. So there are empty positions Commented Jul 1, 2017 at 11:53
  • if (2*prevEntry == arrA[i]){ This line. Commented Jul 1, 2017 at 11:56
  • Whenever you don't know where it crashes, stick to a try-catch block with a 'break' in it or print something in the log like the variable 'i'. And as already mentioned - pushing will solve it. Commented Jul 1, 2017 at 12:06

3 Answers 3

1

You may want to push:

for(let i=0; i <arrA.length; i++){
  if (2*prevEntry == arrA[i]){
    prevEntry *= 2;
    arrB.push((Math.pow(arrA[i], 2)).toString());
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

When you add element to array at specific index, every not defined previously index becomes initialized with undefined value.

For example when you have

var array = [];
array[3] = 1

console log will provide an output

[undefined, undefined, undefined, 1]

so the solution is , as Jonas wrote, to simply push the elements to array instead of inserting them at specific index.

2 Comments

oh my god... i am sorry, that's such a stupid mistake! I should have seen that myself.
In node.js it looks differently: [ <3 empty items>, 1 ] and in Opera - [empty × 3, 1]
0

Due to this line 2*prevEntry == arrA[i], your code was skipping some of the indexes in arrA and Since the indexes of both arrA and arrB were same, arrB had no value i.e. undefined there. Instead of inserting square in arrB by index, use push(), this will only insert squared number.

function foo(arrA){
  if(!arrA || arrA[0]===0)
    return undefined;

  let arrB =[];
  let prevEntry = 1;

  for(let i=0; i <arrA.length; i++){
    if (2*prevEntry == arrA[i]){
      prevEntry *= 2;
      arrB.push(Math.pow(arrA[i], 2)).toString();
    }
  }
  return arrB;
}
console.log(foo([2,4,6,8,9,15,16,27]));

Comments

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.