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

达蒙

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

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

一定的表现

有几个问题。该函数采用的参数str,但您没有使用任何参数调用它。引用引用您要在其上调用方法的实例化对象的常规方法是使用this,但是您具有箭头功能-最好使用标准功能,因此可以使用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());

但是更改内置对象是很糟糕的做法-考虑改用独立功能:

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));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章