javascript - this .join(this) 在 javascript 中如何工作?

标签 javascript arrays

在这种情况下说:

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("|") === "|||"

thisString.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/

相关文章:

javascript - 无法读取未定义的属性 'bind',React.js

php - 从 php 数组中复制一个元素

javascript - Javascript 中的对象数组仅返回某些属性

php - 如何使PHP中的数组打印唯一?

c++ - 零长度 C 数组绑定(bind)到指针类型

javascript - Django-Chartit 'source' 必须是查询集、模型或管理器

javascript - 声音云和Javascript : upload music from stream

javascript - 在 HTML 表格中模拟 Excel 的 "freeze cells"

javascript - 滑过导航栏

java - 如何确保 Map<String, Object> 中的 Java 数组在 GSON toJson 和 fromJson 后保持其类型