簡體   English   中英

為什么我不能在 forEach() 中更改數組的元素?

[英]Why I can't change element of the array in forEach()?

這是我的 function。它應該返回backgroundColor而不是backgroundcolor

我的問題是什么?

 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'

  1. 你需要一個 map
  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"));

更接近您的舊代碼

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

item是 function 中的局部變量。分配給它對newStr沒有影響。

item.toLowerCase()返回一個新字符串,它不會就地修改字符串(JS 字符串是不可變的)。 您需要將其分配回變量以更改它。

使用map()而不是forEach()以便返回一個包含結果的新數組。

 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM