• Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Precios
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

139
Vistas
Switch statement within function returns "undefined" for no obvious reason

I am trying to create a simplistic function which uses a switch statement to return a weighted number. For my use case, the solution is most befitting, however I am getting "undefined" as the result for no obvious reasons. If anyone could point out the mistake, I'm making.

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  switch (n) {
    case n < 70:
      return 1;
    case n < 80:
      return 2;
    case n < 90:
      return 3;
    case n < 100:
      return 4;
  }
}

temp = randomCase();

console.log(temp);

I tried to debug with Chrome developer tool and figure out what might be causing this, but of no avail. It seems there is something obvious I'm missing. (Still learning JS)

9 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As VLAZ mentioned in the comments, a switch statement checks for equality.

You'll want to use an if statement instead:

function randomCase() {
  let n = Math.floor(Math.random() * 100);

  if (n < 70) {
    return 1;
  } else if (n < 80) {
    return 2;
  } else if (n < 90) {
      return 3;
  } else if (n < 100) {
      return 4;
  }
}

temp = randomCase();

console.log(temp);

9 months 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 empleo Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.