Home > Blockchain >  what are the mistake in this code, its giving me NaN
what are the mistake in this code, its giving me NaN

Time:06-13

Why this code giving me NaN as an output???

var rob = function(nums) {
  var a = 0;
  var b = 0;
  for (let i = 0; i < nums.length; i  ) {
    a  = nums[i]   nums[i   2]
    b  = nums[i   1]   nums[i   2]
  }
  return a
};
console.log(rob([1, 2, 3, 1]));

CodePudding user response:

You iterate through the array nums and then trying to access its members beyond its last element.

When i is 3, nums[i 2] refers to nonexisting element, yielding undefined, and when you add a number to undefined, you get NaN.

CodePudding user response:

There are four items in the array [1, 2, 3, 1]. The issue is i 2.

In third iteration of the loop, you are trying to access an index that doesn't exist: nums[i 2] in third iteration becomes nums[2 2], which becomes nums[4]. But nums[3] is the last item, because the array length is only 4

CodePudding user response:

When i, the index of the array nums is out of bounds nums[i] is undefined. And when you add any undefined to any number or NaN the result is NaN.

You can use nums[i 2] || 0 and nums[i 1] || 0 to avoid dealing with undefined. If your aim is to sum all elements with an even index, 0,2 ..., and put the result in a, a better approach might be as below. For a larger array you run the danger of adding some elements to the result more than once.

However, if that's your goal then you can retain nums[ 2] || 0 and nums[i 1] || 0.

const rob = function(nums) {
  let a = 0;
  let b = 0;
  for (let i = 0; i < nums.length; i = i   2) {
    a  = nums[i];
    b  = nums[i 1] || 0;
  }
  return a;
};
console.log(rob([1, 2, 3, 1]));

  • Related