gpt4 book ai didi

javascript - 使用大写每个单词的第一个字母

转载 作者:行者123 更新时间:2023-11-28 13:04:35 25 4
gpt4 key购买 nike

这学期我正在上一门关于 javascript 的类(class),本周的练习之一是取一串单词,并将每个单词的第一个字母大写。我使用 .map() 做到了这一点,代码在这里:

let t1 = "hello how are you doing".split(" ");

let t2 = t1.map(function(word) {
return word[0].toUpperCase() + word.slice(1);
});
console.log(t2.join(" "));

而且它工作得很好。但是,我想知道为什么当我尝试使用 forEach() 时,我无法使其工作。这是我的代码:

let t1 = "hello how are you doing".split(" ");


t1.forEach(function(word) {
word[0] = word[0].toUpperCase();
})
console.log(t1.join(" "));

我对 forEach() 的理解是它循环遍历表中的每个元素,很像一个简单的 for 循环。那么我的代码不应该采用每个单词的第一个字母,并将其替换为应用 toUpperCase() 的相同字母吗?

编辑:我已经知道如何将每个单词的第一个字母大写,我只是询问不同的方法

最佳答案

首先,JS中的字符串是不可变的。

var str = 'hello World';
str[0] = 'H';
console.log(str)

因此word[0] =不会有任何效果。

其次,即使是这样,您也正在更新参数变量的值,而不是数组中的值。

var a = [1, 2, 3];

a.forEach(function(n) {
n = n * 2;
});

console.log(a)

根据与@ deceze的讨论,这一点并不准确。

If a string was mutable, that would have worked just fine. Your "Second" doesn't really apply. – deceze


@deceze Objects are assigned using reference, so it will have the effect. Primitive values are assigned using value. So n in my understanding will always be a copy of item in array. Any manipulation relating to it should not affect the item in array. And string being a primitive value, I mentioned it. Also, I can't think of any variable that has property and is of primitive type. If you have any idea please let me know. Would be glad to learn. :-) – Rajesh


Sure, you're right about that. That's why I'm saying if it was mutable in the first place… Since it's not, the point is moot either way. – deceze

<小时/>

要获得所需的效果,您必须覆盖数组中的值。

let t1 = "hello how are you doing".split(" ");


t1.forEach(function(word, index) {
t1[index] = word[0].toUpperCase() + word.substring(1);
})
console.log(t1.join(" "));

引用:

关于javascript - 使用大写每个单词的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47435404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com