JavaScript 中的 repeat() 方法是用于将字符串重复指定次数的方法。它接受一个整数参数 n,并返回一个新字符串,该字符串是原始字符串重复 n 次的结果。

例如,以下代码将字符串 "hello" 重复三次:

const str = "hello";
const repeatedStr = str.repeat(3);
console.log(repeatedStr); // 输出 "hellohellohello"

如果传递的参数是小数或负数,则会抛出 RangeError。如果传递的参数是 0 或 Infinity,则会返回一个空字符串。

const str = "hello";
// 抛出 RangeError
console.log(str.repeat(-1.5)); 
// 输出 ""
console.log(str.repeat(0)); 
// 输出 ""
console.log(str.repeat(Infinity)); 

需要注意的是,repeat() 方法是一个新的 ES6 方法,因此在旧的浏览器版本中可能不被支持。如果需要在旧版本的浏览器中使用该方法,可以使用 polyfill 或者手写一个类似的实现。

js repeat 用法

原文地址: https://www.cveoy.top/t/topic/ufk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录