JavaScript--Algorithm--Repeat string

The title comes from freecodecamp.

Repeat a given string (first parameter, str) num (second parameter) times. If num is not a positive number, an empty string is returned.

The following are 3 different methods:

// 1. Array, fill, join
function multiStr(str, num){
	return num > 0
		? (new Array(num).fill(str).join(""))
		: "";
}

// 2.递归-if判断
function repeatStringNumTimes(str, num) {
  if (num < 1) {
    return "";
  } else if (num === 1) {
    return str;
  } else {
    return str + repeatStringNumTimes(str, num - 1);
  }
}

//3.递归-三目
function repeatStringNumTimes(str, num) {
  return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}

Realization effect:

 

Implementation code:

<!DOCTYPE html>
<html>
<body>
<p id="id1"></p>
<p id="id2"></p>
<p id="id3"></p>
</body>
<script>

// 1. Array, fill, join
function multiStr(str, num){
	return num > 0
		? (new Array(num).fill(str).join(""))
		: "";
}

// 2.递归-if判断
function repeatStringNumTimes(str, num) {
  if (num < 1) {
    return "";
  } else if (num === 1) {
    return str;
  } else {
    return str + repeatStringNumTimes(str, num - 1);
  }
}

//3.递归-三目
function repeatStringNumTimes2(str, num) {
  return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}

let strResult1 = multiStr("abc", 4);
let strResult2 = repeatStringNumTimes("cdd",2);
let strResult3 = repeatStringNumTimes2('ee1', 5);

document.getElementById("id1").innerHTML = strResult1;
document.getElementById("id2").innerHTML = strResult2;
document.getElementById("id3").innerHTML = strResult3;

</script>


</html>

Guess you like

Origin blog.csdn.net/u013362192/article/details/107851621