【问题标题】:writing prototype to check if string is uppercase编写原型以检查字符串是否为大写
【发布时间】:2016-03-19 21:31:43
【问题描述】:

我正在尝试编写一个字符串原型来检查字符串是否全部大写。这是我到目前为止所拥有的,我不确定为什么这不起作用。

String.prototype.isUpperCase = function(string) {
  if(string === string.toUpperCase()) {
    return true;
  }else{
    return false;
 }
}

我希望它像这样工作:

'hello'.isUpperCase() //false
'Hello'.isUpperCase() //false
'HELLO'.isUpperCase() //true

【问题讨论】:

    标签: javascript string uppercase


    【解决方案1】:

    原型方法接收this 中的实例,而不是您的代码所期望的第一个参数。试试这个:

    String.prototype.isUpperCase = function() {
      return String(this) === this.toUpperCase();
    }
    

    String(this) 调用确保 this 是一个字符串原语,而不是一个字符串对象,它不会被 === 运算符识别为相等。

    【讨论】:

      【解决方案2】:

      您正在测试第一个参数(undefined 在所有三种情况下,因为您没有传递任何参数)而不是字符串本身(应该是 this,而不是 string)。

      【讨论】:

      • 好的,这是有道理的,谢谢你的澄清!
      猜你喜欢
      • 1970-01-01
      • 2017-12-24
      • 2014-08-13
      • 2014-03-26
      • 2018-06-13
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多