在这种情况下说:
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 次?我在理解返回声明时也有些困惑。如果我理解正确,请告诉我:
(if count < 1){
return ''
} else {
return new Array(count + 1).join(this) //This I don't understand.
谢谢。
最佳答案
它创建了一个给定长度的新数组,比如 7。然后你用一个字符串连接所有这些空项,最终重复该字符串 6 次。
通常:
[1,2,3].join("|") === "1|2|3"
然后用一个长度为 4 的数组:
new Array(4).join("|") === "|||"
this
在 String.prototype
方法中引用字符串对象,该函数作为方法被调用:
"hello".bold(); //this would refer to a string object containing "hello" inside bold()
关于javascript - this .join(this) 在 javascript 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835941/