JavaScript字符串repeat()


JavaScript String repeat()方法通过将给定字符串复制并连接指定的次数来返回新字符串 。

repeat()方法的语法为:

str.repeat(count)

在这里, str是一个字符串。


repeat()参数

repeat()方法采用:

  • count0+ Infinity之间的整数,指示重复字符串的次数。

从repeat()返回值
  • 返回一个新字符串,其中包含给定字符串的指定副本数。

注意 :如果重复计数为负,无穷大或最大字符串大小溢出,则repeat()会引发RangeError


示例:使用repeat()方法
let sentence = "Happy Birthday to you! ";

let repeat1 = sentence.repeat(2);
console.log(repeat1); // 'Happy Birthday to you! Happy Birthday to you!'

// count is converted to integer
let repeat2 = sentence.repeat(3.5);
// 'Happy Birthday to you! Happy Birthday to you! Happy Birthday to you!'
console.log(repeat2);

let repeat3 = sentence.repeat(0);
console.log(repeat3); // ''

// RangeError if count is negative or infinite
let repeat4 = sentence.repeat(-1);
console.log(repeat4); // RangeError: Invalid count value

输出

Happy Birthday to you! Happy Birthday to you! 
Happy Birthday to you! Happy Birthday to you! Happy Birthday to you! 

error: Uncaught RangeError: Invalid count value

推荐读物: JavaScript String concat()

Made with ❤️ in Chengdu. Copyright reserved 2019-2022.

蜀ICP备20006366号-1