Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

356
Vistas
what are the mistake in this code, its giving me NaN

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda