JavaScript 如何使用原型定义一个计算字符串实际长度的新方法
在JavaScript中,您可以使用String.length属性获取字符串变量的长度。无论是什么字符串,这个方法都会给您一个带引号的字符串。然而,使用String.length方法也会遇到一些问题。接下来我们讨论一下在使用String.length方法时遇到的问题以及如何解决它。
语法:
string.length
在这里,一个字符串可以是一个具有字符串值的变量,也可以是直接用引号(” “)括起来的字符串。
示例1:
JavaScript
<script>
// Declaring the String with value => "Hello Geeks"
let str1 = "Hello Geeks";
// Printing the length of given string str on console
console.log(str1.length);
</script>
输出:
11
说明: 字符串 str1 的值为“Hello Geeks”,长度为 11。我们可以直接通过自己数值方法获得 11。请记住,length 方法会在遇到任何字符时进行计数,即使是遇到空格也会计数。
示例 2:
JavaScript
<script>
// Declaring the String with value => " Hello Geeks "
let str2 = " Hello Geeks ";
// Printing the length of given string str on console
console.log(str2.length);
</script>
输出:
15
解释: String str2的值为”Hello Geeks”,使用length方法计算出的长度为15。但是实际上,str2字符串的长度为11,因为length方法计算的是被引号括起来的字符的长度,无论它是什么。
但是我们需要的是实际长度,我们可以通过定义String对象的原型来实现。在定义中,我们将定义该操作的实现。
让我们看一下使用原型定义的新truelength方法的实现。
变量”geeks”是一个String对象,该对象包含了length方法,该方法给出了计算空格的长度,所以我们将通过定义字符串对象的原型来修改length方法的名称为truelength。String对象的trim()方法将返回去除了字符串开头和结尾的空格的字符串。我们将获得修剪后的字符串,然后我们可以计算给定字符串的长度,该字符串的长度将是没有开头和结尾空格的实际字符串长度。
Javascript
<script>
// Declaring the String with value => " Hello Geeks ".
let geeks = " Hello Geeks ";
// Defining the prototype for the string object.
String.prototype.truelength = function(){
// trim() method for removing the white
// spaces from the start of the
// string as well as end of the string.
console.log(this.trim().length);
}
// calling the truelength method which we
// defined by the prototype.
geeks.truelength();
</script>
输出:
11
极客教程