Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
¿Cuál es la mejor manera de escribir if-then-else para un gran conjunto de datos en JavaScript?

Estoy tratando de escribir declaraciones condicionales para un gran conjunto de datos en JavaScript. El objetivo es calcular la ingesta de calorías (resultados) en función de la edad y el estilo de vida.

Aquí hay un ejemplo:

HTML

 <label>Enter Age (2 to 100)</label> <input id="getAge" type="text" placeholder="" /> <label>Enter 1 for Sedentary, 2 for Moderate, 3 for Active</label> <input id="getLifeStyle" type="text" placeholder="" />

JavaScript:

 let age, lifestyle, calorie; age = document.getElementById("getAge").value lifestyle = document.getElementById("getLifeStyle").value // two if (age==2) { if (lifestyle==1) { calorie=1000 } if (lifestyle==2) { calorie=2000 } .... // three else if (age==3) { if (lifestyle==1) { calorie=1000 } if (lifestyle==2) { calorie=2000 }.... // four...and so, until 100 // Show calorie console.log("Calorie: "+calorie)

Esto es lo que estoy tratando de lograr:

ingrese la descripción de la imagen aquí

Básicamente repite lo anterior varias veces. No soy un experto en JavaScript. Si bien lo anterior funciona bien para obtener los resultados, no creo que esta sea la forma más eficiente de escribir if-then-else. ¿Hay otras opciones eficientes en JavaScript para hacer esto?

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Un objeto anidado indexado por edad, luego indexado por estilo de vida funcionaría.

 const calorieData = { 2: { 1: 1000, 2: 2000, }, 3: { 1: 1000, 2: 2000, } }; // ... const calories = calorieData[age][lifestyle];

Una versión DRY-er usaría arreglos en su lugar, pero podría requerir un código un poco más confuso debido a los índices basados en 0.

 const calorieData = [ // omit index 0 , // omit index 1 , [1000, 2000], [1000, 2000], // ... ]; // ... // because lifestyle is 1-indexed const calories = calorieData[age][lifestyle - 1];
about 4 years ago · Santiago Gelvez Report

0

const LIFE_STYLE = { SEDENTARY: '1', MODERATE: '2', ACTIVE: '3' } const data = [ { age: 2, lifeStyle: LIFE_STYLE.SEDENTARY, calories: 1000 }, { age: 3, lifeStyle: LIFE_STYLE.SEDENTARY, calories: 1000 } ] const getCaloryData = (age, lifestyle) => { const entry = data.find(entry => entry.age === age && entry.lifeStyle === lifestyle) return entry ? entry.calories : undefined; }

La complejidad es mayor pero la legibilidad es mejor.

about 4 years ago · Santiago Gelvez Report

0

la forma alternativa mejor y más corta para eso es usar el operador ternario 👇

 // two {age == 2 && lifestyle == 1 && calorie = 1000} {age == 2 && lifestyle == 2 && calorie = 2000} //three {age == 3 && lifestyle == 1 && calorie = 1000} {age == 3 && lifestyle == 2 && calorie = 2000} // until 100
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!