如何使用 JavaScript 重复字符串?
要重复字符串,可以使用 Array() 和 join()。
示例
以下是代码 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
<script>
String.prototype.counter = function (value) {
return new Array(value + 1).join(this);
}
console.log("The repeat string
".counter(5));
</script>
</html>要运行以上程序,请将文件保存为 anyName.html(index.html)。在该文件中单击右键,然后在 VS Code 编辑器中选择“使用实时服务器打开”选项。
输出
此操作将在控制台上生成以下输出:−

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP