在这种情况下说:
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..."
Run Code Online (Sandbox Code Playgroud)
它如何添加3次新语句?在理解return语句时我也有些困惑.如果我理解正确,请告诉我:
(if count < 1){
return ''
} else {
return new Array(count + 1).join(this) //This I don't understand.
Run Code Online (Sandbox Code Playgroud)
谢谢.
它创建一个给定长度的新数组,比如7.然后用一个字符串连接所有这些空项,最后重复该字符串6次.
一般:
[1,2,3].join("|") === "1|2|3"
Run Code Online (Sandbox Code Playgroud)
然后使用长度为4的数组:
new Array(4).join("|") === "|||"
Run Code Online (Sandbox Code Playgroud)
this在String.prototype方法内部引用该函数作为方法调用的字符串对象:
"hello".bold(); //this would refer to a string object containing "hello" inside bold()
Run Code Online (Sandbox Code Playgroud)