gpt4 book ai didi

javascript - 将对象内的数组内的字符串元素大写

转载 作者:行者123 更新时间:2023-11-28 11:43:16 24 4
gpt4 key购买 nike

我有这个对象:

let result = {
'i was sent': ["I was sent", "you were Awesome!"],
'to earth': ["to Earth" , "To moon"],
'to protect you': ["to protect you"]
}

如果我们想要将数组中所有元素的每个首字母大写并返回结果,如下所示:

 let result = {
'i was sent you to': ["I was sent", "You were Awesome!"],
'to earth': ["To Earth" , "To moon"],
'to protect you': ["To protect you"],
}

我尝试过此操作,但没有成功(请注意,大写函数适用于字符串):

Object.keys(result).forEach(function(key) {

result[key].forEach(function(e) {
capitalize(result[key][e]);
});
});

console.log(result)

function capitalize(s) {
let first_char = /\S/;
return s.replace(first_char, function(m) {
return m.toUpperCase();
});

}

最佳答案

capitalize() 不会就地修改字符串,您需要使用返回的值。您可以使用 .map() 创建结果数组并将其分配回对象元素。

let result = {
'i was sent': ["I was sent", "you were Awesome!"],
'to earth': ["to Earth", "To moon"],
'to protect you': ["to protect you"]
}

Object.keys(result).forEach(function(key) {
result[key] = result[key].map(capitalize);
});

console.log(result)

function capitalize(s) {
let first_char = /\S/;
return s.replace(first_char, function(m) {
return m.toUpperCase();
});
}

关于javascript - 将对象内的数组内的字符串元素大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59725148/

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