我创建了自己的方法,它基本上将字符串中每个单词的第一个字母大写。
但是,我收到此Uncaught TypeError: Cannot read property 'split' of undefined
错误。我哪里错了?
String.prototype.toCapitalize = (str) => {
let splits = str.split(" ");
let capitalize = '';
splits.forEach((el) => {
let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();
capitalize = capitalize + ' ' + result;
});
return capitalize;
}
let h = 'its a beautiful weather';
h.toCapitalize();
答案 0 :(得分:3)
你怎么认为第一个参数是字符串?它应该是this
。用str
替换this
并使用:
String.prototype.toCapitalize = function () {
let splits = this.split(" ");
let capitalize = '';
splits.forEach((el) => {
let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();
capitalize = capitalize + ' ' + result;
});
return capitalize;
}
let h = 'its a beautiful weather';
console.log(h.toCapitalize());

答案 1 :(得分:2)
有几个问题。该函数采用str
参数,但您不会使用任何参数调用它。引用您调用方法的实例化对象的传统方法是使用this
,但是您有一个箭头函数 - 更好地使用标准函数,因此您可以使用this
:< / p>
String.prototype.toCapitalize = function() {
let splits = this.split(" ");
let capitalize = '';
splits.forEach((el) => {
let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();
capitalize = capitalize + ' ' + result;
});
return capitalize;
}
let h = 'its a beautiful weather';
console.log(h.toCapitalize());
&#13;
但改变内置对象是可怕的练习 - 考虑使用独立的功能:
const toCapitalize = str => str
.split(' ')
.map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
let h = 'its a beautiful weather';
console.log(toCapitalize(h));
&#13;
答案 2 :(得分:1)
如果您想将toCapitalize
称为h.toCapitalize()
,则需要使用this.split(" ");
,因为您在控制台中未定义str
错误:
String.prototype.toCapitalize = function() {
let splits = this.split(" ");
let capitalize = '';
splits.forEach((el) => {
let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();
capitalize = capitalize + ' ' + result;
});
return capitalize;
}
let h = 'its a beautiful weather';
console.log(h.toCapitalize());
&#13;
否则,如果要在str
函数中使用参数toCapitalize
,则需要将其称为st.toCapitalize(h)
,其中st
可以是任何字符串类型值。
String.prototype.toCapitalize = function(str) {
let splits = str.split(" ");
let capitalize = '';
splits.forEach((el) => {
let result = el.charAt(0).toUpperCase() + el.substr(1, el.length).toLowerCase();
capitalize = capitalize + ' ' + result;
});
return capitalize;
}
let st ='';
let h = 'its a beautiful weather';
console.log(st.toCapitalize(h));
&#13;