简体   繁体   English

使用“map”方法的字符串中的大写字母

[英]Capital letters in a string using the 'map' method

I want to change to make the first letters of the words in the string uppercase, and after translating into an array, I use the map method.我想改成把字符串中单词的首字母大写,翻译成数组后,我用map的方法。 The problem is that inheritance does not work in this method, as I understand it, because when you return the map element, the original string is returned:问题是 inheritance 在此方法中不起作用,据我了解,因为当您返回 map 元素时,将返回原始字符串:

const str = 'dkdg gkdj wijoerbj'
let r = str.split(' ').map((item, index) => {
    item[0] = item[0].toUpperCase()
    return item
})

unchanged first letters will also be returned with such a code entry(is in the map()):未更改的首字母也将与这样的代码条目一起返回(在 map() 中):

item[0] = item[0].toUpperCase()
return item[0]

however, when I return the first line, the letters still become uppercase, but I do not know how to return the rest of the word in this case(is in the map()):但是,当我返回第一行时,字母仍然变成大写,但我不知道如何返回这种情况下单词的rest(在map()中):

return item[0] = item[0].toUpperCase()

why inheritance does not work as it should, tell me, please, and how to add the rest of the word if there are no other options?为什么 inheritance 不能正常工作,请告诉我,如果没有其他选项,如何添加单词的 rest?

You need to cancat the first letter with rest of the string.您需要用字符串的 rest 来识别第一个字母。 Also these two lines item[0] = item[0].toUpperCase();return item though will convert the first letter to uppercase but it will still return the original sting because item represent the original word nut not the modified text这两行item[0] = item[0].toUpperCase();return item虽然会将第一个字母转换为大写,但仍会返回原始字符串,因为item表示原始单词 nut 而不是修改后的文本

 const str = 'dkdg gkdj wijoerbj' let r = str.split(' ').map((item, index) => { return item.charAt(0).toUpperCase() + item.substring(1, item.length) }); console.log(r)

We can do this with two array map methods as bellow.我们可以使用两个数组 map 方法来做到这一点,如下所示。

 const str = 'dkdg gkdj wijoerbj'; let r = str.split(' ').map((item, index) => { return ([...item].map((letter, i) => { return (i == 0)? letter.toUpperCase(): letter; })).join(''); }); console.log(r);

 const str = 'dkdg gkdj wijoerbj' let r = str.split(' ').map(x=> x[0].toLocaleUpperCase()); console.log(r)

u can try this code to get first letters of the words in the string uppercase into new arry using map and returns capital letter of each first letter您可以尝试使用此代码使用 map 将字符串大写中单词的首字母转换为新数组并返回每个首字母的大写字母

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM