今天刷题,有个地方需要将某个字符串重复n次返回,可以使用 for 循环进行 concat,后面发现JavaScript中有一个指定重复字符串的方法。
语法
/**
* str: String
* count: Number
*/
let resultString = str.repeat(count);
例子
"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0) // ""
"abc".repeat(1) // "abc"
"abc".repeat(2) // "abcabc"
"abc".repeat(3.5) // "abcabcabc" 参数count将会被自动转换成整数.
"abc".repeat(1/0) // RangeError: repeat count must be positive and less than inifinity
({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)
//"abcabc",repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.
在 Python 中如果要实现相同效果,直接相乘即可:
s = 'abc';
cout = 3;
repeat = count * s // 'abcabcabc'