[英]How to define a javascript string.length() function?
我正在尝试将 java 代码转换为 javascript (js),我对 js 如何缺少许多字符串方法感到非常沮丧。 我知道 js 字符串库,并且您可以执行 someString.length 来获取字符串的长度。 但是我惊喜地看到这个主题的最佳答案: 如何检查字符串“StartsWith”是否是另一个字符串? 可以在我自己的 js 代码文件中定义 startsWith 方法,如下所示:
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
所以我尝试对 length 方法做类似的事情:
if (typeof String.prototype.length != 'function') {
String.prototype.length = function (){
return this.length;
};
}
var str = "a string";
alert(str.length());
但它不起作用,当我尝试调用时,我在 chrome 中收到以下错误: Uncaught TypeError: Property 'length' of object is not a function
有谁知道为什么我不能像上面解释的 startsWith(str) 方法那样创建 length() 函数? 谢谢,基思
String 实例是使用不可变的length
属性创建的,该属性不是从 String.prototype 继承的。 因此,您将无法为字符串创建length()
方法。
见http://ecma-international.org/ecma-262/5.1/#sec-15.5.5
String 实例从 String 原型对象继承属性,它们的 [[Class]] 内部属性值为“String”。 String 实例还有一个 [[PrimitiveValue]] 内部属性、一个 length 属性和一组带有数组索引名称的可枚举属性。
并参见http://ecma-international.org/ecma-262/5.1/#sec-15.5.5.1
一旦创建了一个 String 对象,这个属性就不会改变。 它具有属性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。
这很简单。 只需实现对象的原型。
// Defines the name what You want
String.prototype.size = function () {
return this.length;
}
'abc'.size ();
如果您想要一些不错的实现,请继续:
// Defines the name what You want
String.prototype.untilChar = function (charEnding) {
return charEnding && this.includes (charEnding) ? this.substr (0, this.indexOf (charEnding)).length : this.length;
}
'abcdefg'.untilChar ('d'); // Returns 3
'abcdefg'.untilChar ('z'); // Returns 7
如果你不能得到正确的解决方案,甚至不要尝试运行! ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.