I want to create a string by concatenating multiple copies of another in CoffeeScript or JavaScript.
Do I have to create my own function for this or is there a shortcut like in Python?
I want to create a string by concatenating multiple copies of another in CoffeeScript or JavaScript.
Do I have to create my own function for this or is there a shortcut like in Python?
您可以使用此快捷方式(需要传递重复次数加 1):
Array(6).join 'x'
这将出现在下一版本的 ECMAScript 中,因此您不妨将其实现为 shim。
http://wiki.ecmascript.org/doku.php?id=harmony:string.prototype.repeat
从提案中:
Object.defineProperty(String.prototype, 'repeat', {
value: function (count) {
var string = '' + this;
//count = ToInteger(count);
var result = '';
while (--count >= 0) {
result += string;
}
return result;
},
configurable: true,
enumerable: false,
writable: true
});
然后.repeat()
从字符串调用:
"x".repeat(5); // "xxxxx"
您可以使用 array.join(JavaScript)。大批()
function extend(ch, times){
return Array(times+1).join('x');
}
extend('x', 5);