1. 使用while循环

  1. let str = 'abc'
  2. console.log(str.repeat(2));
  3. String.prototype._repeat = function () {
  4. let res = '', i = 0
  5. while (i < arguments[0]) {
  6. res += this.toString()
  7. i++;
  8. }
  9. return res
  10. }
  11. console.log(str._repeat(3));

2. 插空法

  1. let str = 'abc'
  2. console.log(str.repeat(2));
  3. String.prototype._repeat = function () {
  4. return (new Array(arguments[0] + 1)).join(this.toString());
  5. }
  6. console.log(str._repeat(3));