Home > Back-end >  Why I can't change element of the array in forEach()?
Why I can't change element of the array in forEach()?

Time:10-08

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

What's my problem?

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'

CodePudding user response:

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

CodePudding user response:

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'

  • Related