在JavaScript中重复字符串的三种方法

在这里中,我将解释如何解决freeCodeCamp的“重复重复重复字符串”挑战。这涉及重复一个字符串一定次数。

我将介绍三种方法:

  1. 使用while循环
  2. 使用递归
  3. 使用ES6重复()方法

算法挑战说明

重复给定的字符串(第一个参数)num次(第二个参数)。如果num不是正数,则返回一个空字符串。

function repeatStringNumTimes(str, num) {
     
  return str;
}
repeatStringNumTimes("abc", 3);

提供的测试用例

repeatStringNumTimes("*", 3) should return "***".

repeatStringNumTimes("abc", 3) should return "abcabcabc".

repeatStringNumTimes("abc", 4) should return "abcabcabcabc".

repeatStringNumTimes("abc", 1) should return "abc".

repeatStringNumTimes("*", 8) should return "********".

repeatStringNumTimes("abc", -2) should return "".

方法1:使用While循环重复字符串

只要指定条件的值为true,while语句就会执行其语句。

一会儿语句看起来像这样:

while (condition)
  statement

条件,条件在每次通过循环之前进行评估。如果条件为真,则执行该语句。如果条件为假,则在while循环后继续执行任何语句。

只要条件为真,就执行该语句。解决方法如下:

function repeatStringNumTimes(string, times) {
     
  // Step 1. Create an empty string that will host the repeated string
  var repeatedString = "";

  // Step 2. Set the While loop with (times > 0) as the condition to check
  while (times > 0) {
      // As long as times is greater than 0, the statement is executed
    // The statement
    repeatedString += string; // Same as repeatedString = repeatedString + string;
    times--; // Same as times = times - 1;
  }
  /* While loop logic
                      Condition       T/F       repeatedString += string      repeatedString        times
    First iteration    (3 > 0)        true            "" + "abc"                  "abc"               2
    Second iteration   (2 > 0)        true           "abc" + "abc"               "abcabc"             1
    Third iteration    (1 > 0)        true          "abcabc" + "abc"            "abcabcabc"           0
    Fourth iteration   (0 > 0)        false
    }
  */
  
  // Step 3. Return the repeated string
  return repeatedString; // "abcabcabc"
}

repeatStringNumTimes("abc", 3);

再说一次,不加注释:

function repeatStringNumTimes(string, times) {
     
  var repeatedString = "";
  while (times > 0) {
     
    repeatedString += string;
    times--;
  }
  return repeatedString;
}
repeatStringNumTimes("abc", 3);

方法2:使用条件和递归重复字符串

递归是一种迭代操作的技术,方法是使函数重复调用自身直到获得结果。为了使其正常工作,必须包含递归的一些关键功能。

  • 第一个是基本情况:这是一个语句,通常在条件子句(如)中if,该语句停止递归。
  • 第二种是递归的情况:这是在其自身上调用递归函数的语句。

解决方法如下:

function repeatStringNumTimes(string, times) {
     
  // Step 1. Check if times is negative and return an empty string if true
  if (times < 0) {
     
    return "";
  }
  
  // Step 2. Check if times equals to 1 and return the string itself if it's the case.
  if (times === 1) {
     
    return string;
  }
  
  // Step 3. Use recursion
  else {
     
    return string + repeatStringNumTimes(string, times - 1); // return "abcabcabc";
  }
  /* 
    First Part of the recursion method
    You need to remember that you won’t have just one call, you’ll have several nested calls
                     times       string + repeatStringNumTimes(string, times - 1)
      1st call         3                 "abc" + ("abc", 3 - 1)
      2nd call         2                 "abc" + ("abc", 2 - 1)
      3rd call         1                 "abc" => if (times === 1) return string;
      4th call         0                  ""   => if (times <= 0) return "";
    Second part of the recursion method
      4th call will return      ""
      3rd call will return     "abc"
      2nd call will return     "abc"
      1st call will return     "abc"
    The final call is a concatenation of all the strings
    return "abc" + "abc" + "abc"; // return "abcabcabc";
  */
}
repeatStringNumTimes("abc", 3);

再说一次,不加注释:

function repeatStringNumTimes(string, times) {
     
  if(times < 0) 
    return "";
  if(times === 1) 
    return string;
  else 
    return string + repeatStringNumTimes(string, times - 1);
}
repeatStringNumTimes("abc", 3);

方法3:使用ES6 repeat()方法重复一个字符串

对于此解决方案,你将使用String.prototype.repeat()方法:

  • 该repeat()方法构造并返回一个新字符串,该字符串包含指定数量的字符串(在其上被调用)的副本,并串联在一起。

解决方法如下:

function repeatStringNumTimes(string, times) {
     
  //Step 1. If times is positive, return the repeated string
  if (times > 0) {
      // (3 > 0) => true
    return string.repeat(times); // return "abc".repeat(3); => return "abcabcabc";
  }
  
  //Step 2. Else if times is negative, return an empty string if true
  else {
     
    return "";
  }
}

repeatStringNumTimes("abc", 3);

再说一次,不加注释:

function repeatStringNumTimes(string, times) {
     
  if (times > 0)
    return string.repeat(times);
  else
    return "";
}
repeatStringNumTimes("abc", 3);

你可以将三元运算符用作if / else语句的快捷方式,如下所示:

times > 0 ? string.repeat(times) : "";

可以理解为:

if (times > 0) {
         
    return string.repeat(times);
} else {
     
    return "";
}

然后,你可以在函数中返回三元运算符

关注:Hunter网络安全 获取更多资讯
网站:bbs.kylzrv.com
CTF团队:Hunter网络安全
文章:Sonya Moisset
排版:Hunter-匿名者

你可能感兴趣的:(技术,JavaScript,freeCodeCamp,while,经验分享,安全)