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

197
Views
¿Por qué no puedo cambiar el elemento de la matriz en forEach()?

Aquí está mi función. Se supone que debe devolver backgroundColor en lugar de backgroundcolor .

¿Cuál es mi problema?

 function camelize(str) { let newStr = str.split('-'); newStr.forEach((item, index) => { if (index > 0) { item.toLowerCase(); item = item[0].toUpperCase() + item.slice(1); } }); newStr = newStr.join(''); return newStr; } console.log(camelize("background-color")); //'backgroundсolor' instead of 'backgroundColor'

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. necesitas un mapa
  2. tienes que devolver el artículo

simplifiqué el código

 const camelize = str => str .toLowerCase() .split('-').map((item, index) => index > 0 ? item[0].toUpperCase() + item.slice(1) : item) .join(''); console.log(camelize("background-color")); console.log(camelize("Background-color")); console.log(camelize("BACKGROUND-COLOR"));

Más cerca de su antiguo código

 function camelize(str) { const parts = str.toLowerCase().split('-'); let newStr = parts.map((item, index) => { if (index > 0) { item = item[0].toUpperCase() + item.slice(1); } return item }); newStr = newStr.join(''); return newStr; } console.log(camelize("background-color"));

about 4 years ago · Juan Pablo Isaza Report

0

item es una variable local dentro de la función. Asignarlo no tiene efecto en newStr .

item.toLowerCase() devuelve una nueva cadena, no modifica la cadena en su lugar (las cadenas JS son inmutables). Debe volver a asignarlo a la variable para cambiarlo.

Use map() en lugar de forEach() para que devuelva una nueva matriz con los resultados.

 function camelize(str) { let oldStr = str.split('-'); let newStr = oldStr.map((item, index) => { if (index > 0) { item = item.toLowerCase(); item = item[0].toUpperCase() + item.slice(1); } return item; }); return newStr.join(''); } console.log(camelize("background-color")); //'backgroundсolor' instead of 'backgroundColor'

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!