簡體   English   中英

如何定義一個 javascript string.length() 函數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM