我们试图将一串多个单词拆分成一个单独的单词数组。我们希望将数组中的每个字符串大写。
var titleCase = function(txt) {
var words = txt.split(" ");
words.forEach(function(words) {
if (words === "the" || words === "and") {
return words;
} else {
return words.charAt(0).toUpperCase() + words.slice(1);
};
};
答案 0 :(得分:3)
这里有几个语法错误和Array.forEach
方法的错误用法。请尝试以下方法:
var titleCase = function(txt) {
var words = txt.split(" ");
words.forEach(function(word, idx, array) {
if (word === "the" || word === "and") {
array[idx] = word;
} else {
array[idx] = word.charAt(0).toUpperCase() + word.slice(1);
}
});
return words.join(" ");
};
console.log(titleCase("This is the test"));