JavaScript如何直接修改原数组实现姓名首字母大写
原地修改姓名格式数组的实现方案
问题背景
现有存储姓名的数组如下:
const people = [ "JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR" ];
需求为将每个姓名调整为首字母大写、其余字母小写的格式。
此前通过map方法实现的版本会生成格式化后的新数组,不会改动原数组:
let capitaliseNames = (arr) => { return arr.map((item) => item[0].toUpperCase() + item.slice(1).toLowerCase()); };
当前需要直接修改原数组,尝试使用forEach实现未达到预期。
失效原因
JavaScript中字符串是原始值类型,forEach遍历拿到的item是数组对应位置值的临时拷贝,直接修改item不会同步改动原数组存储的内容,只有通过数组索引直接覆写对应位置的元素,才能真正修改原数组。
正确实现
forEach 版本
在forEach回调中获取当前元素的索引,将格式化后的值赋值给数组对应索引位即可:
const capitaliseNamesInPlace = (arr) => { arr.forEach((item, index) => { arr[index] = item[0].toUpperCase() + item.slice(1).toLowerCase(); }); }; // 调用后原数组会被直接修改 capitaliseNamesInPlace(people); console.log(people); // 输出结果:["John", "Christiana", "Anthony", "Maria", "James", "Michael", "Jennifer"]
边界提示:如果数组中存在空字符串元素,直接取
item[0]会得到undefined,调用toUpperCase()会抛出错误,可增加非空判断做兼容:const capitaliseNamesInPlace = (arr) => { arr.forEach((item, index) => { arr[index] = item ? item[0].toUpperCase() + item.slice(1).toLowerCase() : ''; }); };
传统for循环版本
也可以用基础for循环实现,逻辑完全一致:
const capitaliseNamesInPlace = (arr) => { for (let i = 0; i < arr.length; i++) { const item = arr[i]; arr[i] = item[0].toUpperCase() + item.slice(1).toLowerCase(); } };
内容的提问来源于stack exchange,提问作者IoanLT
相关产品推荐
相关产品推荐

