[英]Capitalise names - Mutate original array
I have the following array:我有以下数组:
const people = [
"JoHn", "ChrISTiana", "anThoNY", "MARia", "jaMeS", "MIChaEl", "jeNNIFeR"
];
I want to capitalise the first letter of each word and lowercase the rest.我想将每个单词的第一个字母大写,其余的小写。
I have used the following function to generate a new array:我使用以下函数生成了一个新数组:
let capitaliseNames = (arr) => {
return arr.map((item) => item[0].toUpperCase() + item.slice(1).toLowerCase());
};
But how do I mutate the original array?但是我如何改变原始数组呢? I have tried the same approach but using forEach and it doesn't seem to work.
我尝试了相同的方法,但使用了 forEach,但它似乎不起作用。
这将完成工作
let capitaliseNames = (arr) => { arr.forEach((elem, i) => { arr[i] = elem[0].toUpperCase() + elem.slice(1).toLowerCase() }); };
First: toLowerCase()
then you can use a custom function for the mutation the first letter.首先:
toLowerCase()
然后您可以使用自定义函数来突变第一个字母。
UPDATE Use a loop where you can manipulate the original array.更新使用循环,您可以在其中操作原始数组。 For example a for loop.
例如 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)
Use forEach()
instead of map()
and reassign the mutated value back to the original array:使用
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);
Had a go using the for loop and this works:尝试使用 for 循环,这很有效:
let capitaliseNames = (arr) => {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1).toLowerCase();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.