2012-08-06 64 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/