英文:
I am doing a problem that I have to capitalize the first letter of each word in a provided string
问题
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join("");
}
console.log(generateHashtag("i am a good coder"))
这是我想出来的代码,但在迭代字符串后,输出的是一个具有首字母大写的单词的数组。如何将这些单词连接起来,形成没有空格的句子?
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
words.join(" ");
return words
}
console.log(generateHashtag("i am a good coder"))
<!-- end snippet -->
This is the code I have come up with but after iterating the string, the output is an array with the first words capitalized. How do I join up the words from the array to form back the sentence without the spaces?
答案1
得分: 1
Array#join()
返回一个新的 string
。直接返回该值,而不是在没有赋值的情况下在 words
上调用它。
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(" ");
}
console.log(generateHashtag("i am a good coder"));
join()
方法通过使用逗号或指定的分隔符字符串连接数组(或类似数组的对象)中的所有元素创建并返回一个新字符串。如果数组只有一个项,则不使用分隔符将返回该项。
英文:
Array#join()
returns a new string
. Return that value directly instead of calling it on words
without assignment.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(" ");
}
console.log(generateHashtag("i am a good coder"));
<!-- end snippet -->
> The join()
method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
答案2
得分: 1
words.join() 创建一个新值,它不会更新 words 的值。
尝试这样做:
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(' ')
}
console.log(generateHashtag("i am a good coder"))
在这里,我们返回 words.join(' ')。
英文:
words.join() creates a new value, it doesn't update the words value.
Try this:
function generateHashtag(str) {
const words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(' ')
}
console.log(generateHashtag("i am a good coder"))
Here we return words.join(' ')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论