写一个函数,使用你的"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" ]