【转】重复输出⼀个给定的字符串的⼏种⽅法
⽅法1:通过 `while` 循环重复输出⼀个字符串
解题思路:while语句只要指定的条件计算结果为true的时候,就执⾏其语句。while语句的语法是这样的:
字段字符串去重复
1while (expression)
2  statement
在每次通过循环之前计算条件结果。如果条件为true,则执⾏语句。如果条件为false,则执⾏继续 while 循环之后的任何语句。
只要条件为true,语句就会执⾏。这⾥是解决⽅案:
function repeatString(str, times) {
//空字符,⽤来储存重复的字符串
var repeatedString = '';
//当(times>0)时执⾏语句
while (times > 0) {
repeatedString += str;
times--;
}
//返回重复的字符串
return repeatedString;
}
//这⾥是测试
console.log(repeatString('abc', 3));
还可以⽤数组join()拼接字符串,例如:
function res(str, times) {
var resed = [];
while (times > 0) {
resed.push(str);
times--;
}
return resed.join('');
}
console.log(res('abc', 3));
另⼀个变种可以⽤ for 循环:
function res(str, times) {
var resed = '';
for (var i = 0; i < times; i++) {
resed += str;
}
return resed;
}
console.log(res('abc', 3));
⽅法2:通过条件判断和递归重复输出⼀个字符串
递归是⼀种通过重复地调⽤函数本⾝,直到它达到达结果为⽌的迭代操作的技术。为了使其正常⼯作,必须包括递归的⼀些关键特征。
第⼀种是基本情况:⼀个语句,通常在⼀个条件语句(如if)中,停⽌递归。
第⼆种是递归情况:调⽤递归函数本⾝的语句。
这⾥是解决⽅案:
function res(str, times) {
//当times为负数时则返回空字符串
if (times <= 0) {
return '';
}
//如果times为1则返回字符串本⾝
if (times === 1) {
return str;
} //使⽤递归
else {
return str + res(str, times - 1);
}
}
console.log(res('abc', 3));
⽅法3:使⽤ES6 `repeat()` ⽅法重复输出⼀个字符串
这个解决⽅案⽐较新潮,您将使⽤peat() ⽅法:
repeat() ⽅法构造并返回⼀个新字符串,该字符串包含被连接在⼀起的指定数量的字符串的副本。这个⽅法有⼀个参数count表⽰重复次数,介于0和正⽆穷⼤之间的整数 : [0, +∞) 。表⽰在新构造的字符串中重复了多少遍原字符串。重复次数不能为负数。重复次数必须⼩于infinity,且长度不会⼤于最长的字符串。
这⾥是解决⽅案:
function res(str, times) {
//如果times为正数,则返回重复的字符串
if (times > 0) {
peat(times);
}
//如果times为负数,则返回空字符串
else {
return '';
}
}
console.log(res('abc', 3));
您可以使⽤三元表达式作为 if/else 语句的快捷⽅式,如下所⽰:
function res(str, times) {
return times > 0 ? peat(times)  : '';
}
console.log(res('abc', 3));
原⽂链接:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。