我如何将这个回调函数合并到该对象值的所有首字母大写?

  • 本文关键字:对象 回调 合并 函数 javascript
  • 更新时间 :
  • 英文 :


写一个函数,使用你的"fixTitle"函数来固定每个标题,并返回一个字符串数组,其中每个条目都是固定的标题。

function fixTitle(str) {
var words = str.toLowerCase().split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return words.join(' ');
}
console.log(fixTitle("THE HiSTory of mathematiCS")); // "The History Of Mathematics" 
function bookTitle(arr){
var result = [];
for (var i = 0; i < arr.length; i++) {
for (var key in arr[i]) {
result.push(bookTitle(arr[i][key]))
}
}
return result;
}

const books = [
{title: "the midnight sky", author: "Samuel Goodens"},
{title: "technology In THE age of artificial intelligenge", author: "Lara Del Rio"},
{title: "never GIVE up", author: "Michelle Li"}  
];
console.log(bookTitle(books)); //["The Midnight Sky", "Technology In The Age Of Artificial Intelligenge", "Never Give Up" ]

既然知道需要从books中的每个对象访问title属性,就不需要使用for..in循环遍历键。相反,直接使用title键并删除内部循环result.push(fixTitle(arr[i].title))。还要确保在函数中调用正确的函数fixTitle,而不是bookTitle

function fixTitle(str) {
var words = str.toLowerCase().split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return words.join(' ');
}
function bookTitle(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(fixTitle(arr[i].title))
}
return result;
}

const books = [
{title: "the midnight sky", author: "Samuel Goodens"},
{title: "technology In THE age of artificial intelligenge", author: "Lara Del Rio"},
{title: "never GIVE up", author: "Michelle Li"}  
];
console.log(bookTitle(books)); // ["The Midnight Sky", "Technology In The Age Of Artificial Intelligenge", "Never Give Up" ]

相关内容

  • 没有找到相关文章