Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
Why I can't change element of the array in forEach()?

Here's my function. It's supposed to return backgroundColor instead of backgroundcolor.

What's my problem?

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 Respostas
Responde à pergunta

0

  1. You need a map
  2. you need to return the item

I simplified the code

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

Closer to your old code

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 Relatório

0

item is a local variable inside the function. Assigning to it has no effect on newStr.

item.toLowerCase() returns a new string, it doesn't modify the string in place (JS strings are immutable). You need to assign it back to the variable to change it.

Use map() instead of forEach() so you return a new array with the results.

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda