编写原型来检查字符串是否为大写
writing prototype to check if string is uppercase
我正在尝试编写一个字符串原型来检查字符串是否全部为大写。这是我目前所拥有的,我不确定为什么这不起作用。
String.prototype.isUpperCase = function(string) {
if(string === string.toUpperCase()) {
return true;
}else{
return false;
}
}
我希望它像这样工作:
'hello'.isUpperCase() //false
'Hello'.isUpperCase() //false
'HELLO'.isUpperCase() //true
您正在测试第一个参数(在所有三种情况下都是 undefined
,因为您没有传递任何参数)而不是字符串本身(应该是 this
,而不是 string
).
原型方法接收 this
中的实例,而不是您的代码似乎期望的第一个参数。试试这个:
String.prototype.isUpperCase = function() {
return String(this) === this.toUpperCase();
}
String(this)
调用确保 this
是字符串基元而不是字符串对象,后者不会被 ===
运算符识别为相等。
我正在尝试编写一个字符串原型来检查字符串是否全部为大写。这是我目前所拥有的,我不确定为什么这不起作用。
String.prototype.isUpperCase = function(string) {
if(string === string.toUpperCase()) {
return true;
}else{
return false;
}
}
我希望它像这样工作:
'hello'.isUpperCase() //false
'Hello'.isUpperCase() //false
'HELLO'.isUpperCase() //true
您正在测试第一个参数(在所有三种情况下都是 undefined
,因为您没有传递任何参数)而不是字符串本身(应该是 this
,而不是 string
).
原型方法接收 this
中的实例,而不是您的代码似乎期望的第一个参数。试试这个:
String.prototype.isUpperCase = function() {
return String(this) === this.toUpperCase();
}
String(this)
调用确保 this
是字符串基元而不是字符串对象,后者不会被 ===
运算符识别为相等。