如何使用自定义创建的字符串原型方法?

时间:2018-06-18 06:32:27

标签: javascript

我创建了自己的方法,它基本上将字符串中每个单词的第一个字母大写。

但是,我收到此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();

3 个答案:

答案 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>

&#13;
&#13;
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;
&#13;
&#13;

但改变内置对象是可怕的练习 - 考虑使用独立的功能:

&#13;
&#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;
&#13;
&#13;

答案 2 :(得分:1)

如果您想将toCapitalize称为h.toCapitalize(),则需要使用this.split(" ");,因为您在控制台中未定义str错误:

&#13;
&#13;
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;
&#13;
&#13;

否则,如果要在str函数中使用参数toCapitalize,则需要将其称为st.toCapitalize(h),其中st可以是任何字符串类型值。

&#13;
&#13;
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;
&#13;
&#13;