我有以下数组:
const people = [
"JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR"
];我想大写每个单词的第一个字母和小写其余的。
我使用了以下函数来生成一个新的数组:
let capitaliseNames = (arr) => {
return arr.map((item) => item[0].toUpperCase() + item.slice(1).toLowerCase());
};但是我如何改变原始数组呢?我尝试过同样的方法,但是使用了forEach,而且它似乎不起作用。
发布于 2022-06-27 09:29:28
这将完成这项工作。
let capitaliseNames = (arr) => { arr.forEach((elem, i) => { arr[i] = elem[0].toUpperCase() + elem.slice(1).toLowerCase() }); };发布于 2022-06-27 09:26:36
首先:toLowerCase(),然后您可以使用自定义函数对第一个字母进行突变。
UPDATE使用一个可以操作原始数组的循环。例如,For循环。
const people = ["JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR"];
for(let i = 0; i < people.length; i++) {
people[i] = capitalizeFirstLetter( people[i].toLowerCase() ) ;
}
function capitalizeFirstLetter(str) {
return str[0].toUpperCase() + str.slice(1);
}
console.log(people)
发布于 2022-06-27 09:27:02
使用forEach()而不是map(),并将修改后的值重新分配回原始数组:
const people = ["JoHn", "ChrISTiana", "anThoNY", "MARia",
"jaMeS", "MIChaEl", "jeNNIFeR"];
const capitaliseNames = (arr) => arr.forEach(
(v, i, a) => a[i] = v[0].toUpperCase() + v.slice(1).toLowerCase()
);
capitaliseNames(people);
console.log(people);
https://stackoverflow.com/questions/72769703
复制相似问题