为什么我无法更改 forEach() 中的数组元素?

Hea*_*ven 0 javascript arrays string foreach

这是我的功能。它应该返回backgroundColor而不是backgroundcolor.

\n

我的问题是什么?

\n

\r\n
\r\n
function camelize(str) {\n  let newStr = str.split(\'-\');\n  newStr.forEach((item, index) => {\n    if (index > 0) {\n      item.toLowerCase();\n      item = item[0].toUpperCase() + item.slice(1);\n    }\n  });\n\n  newStr = newStr.join(\'\');\n  return newStr;\n}\nconsole.log(camelize("background-color")); //\'background\xd1\x81olor\' instead of \'backgroundColor\'
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

mpl*_*jan 5

  1. 你需要一张地图
  2. 您需要退回该物品

我简化了代码

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")); 
Run Code Online (Sandbox Code Playgroud)

更接近您的旧代码

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"));
Run Code Online (Sandbox Code Playgroud)

  • 一个建议。将“item.toLowerCase()”移到“if”语句之外,以便第一个单词始终小写。否则,该函数将因输入“背景颜色”而中断。 (2认同)