2012-08-06 61 views
1

說,在這種情況下:這個.join(這個)如何在javascript中工作?

String.prototype.times = function(count) { 
    return count < 1 ? '' : new Array(count + 1).join(this); 
} 

"hello!".times(3); //"hello!hello!hello!"; 
"please...".times(6); //"please...please...please...please...please...please..." 

它是如何添加到新語句3倍?我在理解return語句時也有些困惑。請告訴我,如果我正確理解這一點:

(if count < 1){ 
    return '' 
} else { 
    return new Array(count + 1).join(this) //This I don't understand. 

謝謝。

回答

6

它創建一個給定長度的新數組,比如說7.然後,用一個字符串連接所有這些空項目,最終重複該字符串6次。

通常:

[1,2,3].join("|") === "1|2|3" 
與長度爲4的陣列

則:String.prototype方法內

new Array(4).join("|") === "|||" 

this參照字符串對象的函數被稱爲上的方法,包括:

"hello".bold(); //this would refer to a string object containing "hello" inside bold() 
+0

啊我明白了。但爲什麼它必須有7的給定長度?數組是否連接到原始字符串,因爲它是.join(this)? – Sean 2012-08-06 21:13:25

+0

@SeanDokko'7'就是一個例子,你可以在那裏傳遞任何數字作爲參數。如果我說'.times(15)',那麼'count + 1'等於16,這就形成了一個「新的Array(16)」,然後將15個字符串連接在一起。創建的數組不會附加任何東西,它會創建並丟失。 – Esailija 2012-08-06 21:13:42

+0

我明白了。感謝您的進一步澄清。 – Sean 2012-08-06 21:15:20

3

this在本文中指到受影響的字符串。所以如果我打電話"hello".times(5),那麼this將參考"hello"

該功能通過創建一個包含count+1元素的數組,從而有效地使count之間存在「空白」。然後將這些碎片與this字符串粘在一起,導致它this重複count次。

當然,如果被告知重複少於一次,結果是空的。 count < 1檢查是爲了避免無效數組大小的錯誤。

0

該方法創建的給定長度的新的數組,加1。例如:

"hello".times(3); 

創建以下數組:

[undefined × 4] 

然後每個這些陣列元件被連接在一起與.join("hello")。這基本上翻譯出來的:

"" /* undefined array element */ + "hello" /* join string */ + "" + "hello" ... 


是的,你似乎理解三元運算符。

1

.join()會加入數組的單元格,產生一個字符串。例如:

var arr = [ 'one', 'two', 'three' ]; 

var str = arr.join(', '); 

// str is now "one, two, three" 

因此,在你times功能,你說new Array(count + 1)。所以,如果count是3,那麼實際上是製作一個空的陣列的4個單元。然後您加入單元與this(這是字符串)。

0
String.prototype.repeat = function(times) { 
    return new Array(times+1).join(this);  
} 

"go ".repeat(3) + "Giants!"; //"go go go Giants!" 

重點是在分離器的參數,同時基本陣列只包括未定義的部件值。上面的例子可以在普通寫法寫成:

[undefined,undefined,undefined,undefined].join("go ") + "Giants!"; 

隨着聯接運算符,每個陣列成員被轉換成字符串(在這種情況下,一個空字符串)是級聯之前。

來源:https://javascriptweblog.wordpress.com/2010/11/08/javascripts-dream-team-in-praise-of-split-and-join/