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

153
Views
Cómo agregar a una variable global con un valor de retorno de funciones (JavaScript)

Tengo una función de devolución de llamada que toma dos parámetros y una variable global que me gustaría agregar con el valor devuelto por esta función. Sin embargo, la variable sigue siendo la misma. ¡Por favor ayuda!

 let sum = 0; const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}]; function addObjValue(arr, total) { arr.forEach(element => { const val = element.value; total += checkObjValue(val); console.log(total); }) } function checkObjValue(x) { switch(x) { case '2': return 1; break; case '3': return 5; break; } } addObjValue(myArr, sum); // sum remains 0
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede crear una variable local y guardar los totales allí, luego solo devolver el valor total

 function addObjValue(arr) { let total = 0 arr.forEach(element => { const val = element.value; total += checkObjValue(val); console.log(total); }) return total }

Y después de eso, haga que su suma sea igual al valor devuelto

 sum = addObjValue(myArr);

Actualización Una cosa más. Para obtener la suma de una matriz, puede usar el método de reduce

 arr.reduce((totalSum, currenElement) => { return totalSum + currenElement.value }, 0 /*first value of totalSum (by default equal to the first element of the array)*/)
about 4 years ago · Juan Pablo Isaza Report

0

Tema:

  • total está en el ámbito de addObjValue , por lo que no se suma a la sum final
  • Break Inside Switch-Case es inalcanzable ya que viene después return 1;

Puede realizar los siguientes 2 cambios para que funcione.

 let sum = 0; const myArr = [{name: 'dj', value: '2'}, {name: 'kd', value: '3'}]; function addObjValue(arr, total) { arr.forEach(element => { const val = element.value; total += checkObjValue(val); }) return total; // change 1: returning total } function checkObjValue(x) { switch(x) { case '2': return 1; case '3': return 5; } } sum = addObjValue(myArr, sum); // change 2: assigned return value back to sum
about 4 years ago · Juan Pablo Isaza 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!