我正在尝试编写一个函数,只会将名字和姓氏的第一个字母大写......有关如何处理此问题的任何想法?
const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];
function capitalizeNames(peopleArray) {
return peopleArray.toString().toLowerCase().split('').map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(' ').split();
}
// set the resulting array to this variabble
const capitalizedNames = capitalizeNames(namesHardest);
capitalizedNames;
答案 0 :(得分:5)
一个问题是使用array.toString - 这会产生类似
的字符串'emIly sMith angeliNA Jolie braD piTt'
所以,你已经丢失了数组元素
您需要使用array.map
单独处理每个元素function capitalizeNames(peopleArray) {
return peopleArray.map(function(name) {
/* do something with each name *
})
}
您的另一个问题是split('')
将字符串拆分为字符 - 但您希望将其拆分为空格...即split(' ')
现在,我们已经
了function capitalizeNames(peopleArray) {
return peopleArray.map(function(name) {
return name.split(' ').map(function(word) {
/* do something with each part of name *
});
});
}
所以,现在,如何大写字符串 - 你的代码有效,但我更喜欢
word[0].toUpperCase() + word.slice(1).toLowerCase();
把它放在一起,你得到了
function capitalizeNames(peopleArray) {
return peopleArray.map(function(name) {
return name.split(' ').map(function(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
});
});
}
或者,在ES2015 +中,使用箭头功能(因为您的代码使用const
,为什么不使用所有ES2015 +)
const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];
const capitalizeNames = peopleArray => peopleArray.map(name =>
name.split(' ').map(word =>
word[0].toUpperCase() + word.slice(1).toLowerCase()
).join(' ')
);
const capitalizedNames = capitalizeNames(namesHardest);
console.log(capitalizedNames);

答案 1 :(得分:2)
对不起,我迟到了,我宁愿使用带有闭包的array.from
simulating
答案 2 :(得分:0)
let namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];
namesHardest = namesHardest.map(val => {
let [first, last] = val.toLowerCase().split(' ');
first = first.replace(first[0], first[0].toUpperCase());
last = last.replace(last[0], last[0].toUpperCase());
return `${first} ${last}`
});
console.log(namesHardest);

答案 3 :(得分:0)
你的逻辑有点偏。首先,对于每个字符串,您需要按空格拆分以获取名字和姓氏。然后,您可以对每个字符串的第一个字符进行upcase。见下文:
const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];
const capitalizeName = (name) => `${name[0].toUpperCase()}${name.slice(1)}`;
const capitalizeNames = (peopleArray) => peopleArray.map(name => {
const [first, last] = name.toLowerCase().split(' ');
return `${capitalizeName(first)} ${capitalizeName(last)}`;
});
console.log(capitalizeNames(namesHardest))